Fragment的setUserVisibleHint方法实现懒加载

http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2014/1021/1813.html

我们在做应用开发的时候,一个Activity里面可能会以viewpager(或其他容器)与多个Fragment来组合使用,而如果每个fragment都需要去加载数据,或从本地加载,或从网络加载,那么在这个activity刚创建的时候就变成需要初始化大量资源。这样的结果,我们当然不会满意。那么,能不能做到当切换到这个fragment的时候,它才去初始化呢?

答案就在Fragment里的setUserVisibleHint这个方法里。请看关于Fragment里这个方法的API文档

Set a hint to the system about whether this fragment 's UI is currently visible to the user. This hint defaults to true and is persistent across fragment instance state save and restore.
An app may set this to false to indicate that the fragment' s UI is scrolled out of visibility or is otherwise not directly visible to the user. This may be used by the system to prioritize operations such as fragment lifecycle updates or loader ordering behavior.
Parameters
isVisibleToUser true if this fragment's UI is currently visible to the user ( default ), false if it is not.

猜你喜欢

转载自blog.csdn.net/xq_1358531/article/details/44830117
今日推荐