Android fragment懒加载之初探

来源:互联网 发布:apple解压软件 编辑:程序博客网 时间:2024/06/06 02:08

         在Android的开发过程中,会遇到使用使用fragment来切换页面,特别是使用viewpager和fragment来切换页面的时候,由于viewpager的预加载的机制,当显示twofragment时,同时会预加载onefragment和threefragment。如何每个页面中都有大量的耗时操作,比如加载大量的网络图片,会消耗很多内存资源。

        基于这个原因,可以通过设置如果当前fragment ui可见才开始加载数据。就可以解决这个问题了。于是便出现了

   fragment懒加载机制。详细使用可查看如下介绍:

     Fragment的源码中有一个方法  setUserVisibleHint

    源码:

      

** * 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. * * 该方法用于告诉系统,这个FragmentUI是否是可见的。所以我们只需要继承Fragment并重写该方法, *    即可实现在fragment可见时才进行数据加载操作,即Fragment的懒加载。 */
 

    所以可以定义一个基类如下:

     

public abstract class BaseLazyFragment extends Fragment{    protected boolean isVisible;  //判断fragmentUI是否可见        @Override    public void setUserVisibleHint(boolean isVisibleToUser) {        super.setUserVisibleHint(isVisibleToUser);        if(getUserVisibleHint()){  //当前fragment UI可见            isVisible=true;            onVisible();  //可见的操作,可见时才开始加载数据(注意:通过测试发现该方法有可能在onCreateView之前调用,                          // 所以加载数据一定注意有可能会出现空指针异常)        }else{            isVisible=false;            onInvisible(); //执行ui不可见的操作        }    }    protected void onVisible(){        lazyLoad();    }    protected abstract void lazyLoad();    protected void onInvisible(){}}


   子类如下;

  

public abstract class BaseLazyFragment extends Fragment{    protected boolean isVisible;  //判断fragmentUI是否可见        @Override    public void setUserVisibleHint(boolean isVisibleToUser) {        super.setUserVisibleHint(isVisibleToUser);        if(getUserVisibleHint()){  //当前fragment UI可见            isVisible=true;            onVisible();  //可见的操作,可见时才开始加载数据(注意:通过测试发现该方法有可能在onCreateView之前调用,                          // 所以加载数据一定注意有可能会出现空指针异常)        }else{            isVisible=false;            onInvisible(); //执行ui不可见的操作        }    }    protected void onVisible(){        lazyLoad();    }    protected abstract void lazyLoad();    protected void onInvisible(){}}
  相信聪明的你,已经清楚了如何使用fragment的懒加载了


1 0
原创粉丝点击