多个Fragment放到一个Activity里面,Activity启动时会同时加载所有Fragment资源,造成卡顿现象。实际情况我们想要的是只加载当前显示的Fragment资源即可,即懒加载模式,使用Fragment的setUserVisibleHint和getUserVisibleHint 。
下面是一段官方的描述:
* 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.
*
* <p>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.</p>
*
* @param
isVisibleToUser
true if this fragment's UI is currently visible to the user (default),
* false if it is not.
public void
setUserVisibleHint(
boolean
isVisibleToUser)
/**
* @return The current value of the user-visible hint on this fragment.
* @see #setUserVisibleHint(
boolean
)
*/
public boolean
getUserVisibleHint() {
return
mUserVisibleHint
;
}
总结一句就是isVisibleToUser为Ture时此fragment可见,false时不可见
Fragment懒加载实现思路就是把Fragment的资源加载写到一个LazyLoad()函数里面,当fragment可见时对资源进行加载。示例代码如下:
- 在Fragement中重写setUserVisibleHint方法
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if(getUserVisibleHint()){
mIsVisible = true ;
lazyLoad();
}else{
mIsVisible = false ;
}
} - lazyLoad 负责进行耗时操作,这里需要注意判断是否执行过Create,系统执行流程会先执行到setUserVisibleHint 然后执行onCreate最后再去执行setUserVisibleHint,初始化工作放到onCreate里面,加载资源时判断是否已经执行过onCreate方法,否则第一次执行 setUserVisibleHint 方法时会因为没有初始化报空指针异常。
private void lazyLoad(){
if(mIsVisible &&getIsCrearte ()){
//网络请求,资源加载等费事操作
}
}