Fragment懒加载

一、什么是懒加载?

有时候一个Activity里以viewpager与多个Fragment来组合使用。但是如果每个fragment都需要去加载数据,或从本地加载,或从网络加载,那么这个activity刚创建的时候就变成需要初始化大量资源。

显然这样不是很合理,我们希望在切换到这个fragment的时候,它才去初始化,去加载数据。这种方式我们称为懒加载。

二、懒加载的原理

Fragment中提供了一个setUserVisibleHint(boolean isVisibleToUser)的方法,用来获取当前fragment是否已经显示给用户了。我们就根据这个方法,如果返回true就去加载数据,如果返回false就不去加载数据。

    /**
     * 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) {
        if (!mUserVisibleHint && isVisibleToUser && mState < STARTED) {
            mFragmentManager.performPendingDeferredStart(this);
        }
        mUserVisibleHint = isVisibleToUser;
        mDeferStart = !isVisibleToUser;
    }

三、懒加载实现方法

  1. 继承Fragment,增加lazyLoad抽象方法。
public abstract class LazyFragment extends Fragment {  
        protected boolean isVisible;  
        /** 
         * 在这里实现Fragment数据的缓加载. 
         * @param isVisibleToUser 
         */  
        @Override  
        public void setUserVisibleHint(boolean isVisibleToUser) {  
            super.setUserVisibleHint(isVisibleToUser);  
            if(getUserVisibleHint()) {  
                isVisible = true;  
                onVisible();  
            } else {  
                isVisible = false;  
                onInvisible();  
            }  
        }  
      
        protected void onVisible(){  
            lazyLoad();  
        }  
      
        protected abstract void lazyLoad();  
      
        protected void onInvisible(){}  
    } 
  1. 在我们自己定义fragment的地方,继承上面的LazyFragment 。然后是实现抽象方法lazyLoad(),把要加载数据的代码放到这里。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容