安卓Fragment资源懒加载

           多个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可见时对资源进行加载。示例代码如下:
  1.           在Fragement中重写setUserVisibleHint方法
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
       
    super.setUserVisibleHint(isVisibleToUser);
       
    if(getUserVisibleHint()){
           
    mIsVisible = true ;
            lazyLoad();
        }
    else{
           
    mIsVisible = false ;
        }
    }
  2. lazyLoad 负责进行耗时操作,这里需要注意判断是否执行过Create,系统执行流程会先执行到setUserVisibleHint 然后执行onCreate最后再去执行setUserVisibleHint,初始化工作放到onCreate里面,加载资源时判断是否已经执行过onCreate方法,否则第一次执行 setUserVisibleHint  方法时会因为没有初始化报空指针异常。
    private void
    lazyLoad(){
       
    if(mIsVisible &&getIsCrearte ()){
             //网络请求,资源加载等费事操作

        }
    }
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值