android viewpager使用Fragment懒加载,滑到当前fragment才进行数据加载

前言:如果不做fragment的懒加载则每次进入activity就会初始化没必要的数据,消耗内存和网络流量,再每次自动销毁后也需要重新初始化fragment的数据,为此优化,我们要做fragment的懒加载,网络上关于懒加载的文章数不胜数,可是详细、全面,又有实际源码和例子的很少,下面是我摘抄的技术代码,原文地址见文章下面.
PagerFragment里面适配的fragment只需要继承自LazyFragment处理懒加载关系,而LazyFragment继承自BaseFragment,BaseFragment处理fragment初始化控件和fragment销毁时和activity分离的事情
下面献上LazyFragment的源码:

public class LazyFragment extends BaseFragment
{
    private boolean isInit=false;//真正要显示的view是否已经被初始化(正常加载)
    private Bundle savedInstancseState;
    public static final String INTENT_BOOLEAN_LAZYLOAD="intent_boolean_lazyLoad";
    private boolean isLazyLoad=true;//默认状态需要懒加载
    private FrameLayout layout;
    private boolean isStart=false;// 是否处于可见状态,in the screen
    @override 
    protected final void onCreateView(Bundle savedInstancseState)
    {
        super.onCreateView(savedInstancseState);
        Bundle bundle=getArguments();
        if(bundle!=null)
        {
            isLazyLoad=bundle.getBoolean(INTENT_BOOLEAN_LAZYLOAD,isLazyLoad);
        }
        //判断是否懒加载 
        if(isLazyLoad)
        { 
            //一旦isVisibleToUser==true即可对真正需要的显示内容进行加载
            if(getUserVisibleHint()&&!isInint)
            {
                this.savedInstancseState=savedInstancseState;
                onCreateViewLazy(savedInstancseState);
                isInint=true;
            }else{
                 //进行懒加载
                 layout=new FrameLayout(getApplicationContext);
                 layout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
                 View view=LayoutInflater.from(getApplicationContext()).inflate(R.layout.fragment_lazy_loading,null);
                 layout.addView(view);
                 super.setContentView(layout);
            }
        }else
        {
             //不需要懒加载,开门见山,调用onCreateViewLazy正常加载显示内容即可
             onCreateViewLazy(savedInstancseState);
             isInint=true;
        }
    }
    @override
    public void setUserVisibleHint(boolean isVisibleToUser)
    {
       super.setUserVisibleHint(isVisibleToUser);
       Log.d("TAG", "setUserVisibleHint() called with: " + "isVisibleToUser = [" + isVisibleToUser + "]");
       //一旦isVisibleToUser==true即可进行对真正需要的显示内容的加载
       //可见,但还没被初始化
       if(isVisibleToUser&&!isInint&&getContentView()!=null)
       {
           onCreateViewLazy(savedInstancseState);
           isInint=true;
           onResumeLazy();//TODO 
       }
       //已经被初始化(正常加载)过了
       if(isInint&&getContentView!=null)
       {
          if(isVisibleToUser)
          {
             isStart=true;
             onFragmentStartLazy();//TODO
          }else{
              isStart=false;
              onFragmentStopLazy();
          }
       }
       @override
       public void setContentView(int layoutResID)
       {
           //判断若isLazyLoad=true,移除所有lazy view,加载真正要显示的view
           if(isLazyLoad&&getContentView()!=null&&getContentView().getParent()!=null)
           {
                layout.removeAllViews();
                View view=inflater.inflate(layoutResID,layout,false);
                layout.addView(view);
           }else
           {
               super.setContentView(layoutResID);
           }
       }
       @override
       public void setContentView(View view)
       {
           //判断若isLazyLoad=true,移除所有lazy view,加载真正要显示的view
           if(isLazyLoad&&getContentView()!=null&&getContentView().getParent!=null)
           {
              layout.removeAllViews();
              layout.addView(view);
           }else
           {
               //否则开门见山,直接加载
               super.setContentView(view);
           }
       }
       @override
       public final void onStart()
       {
             Log.d("TAG", "onStart() : " + "getUserVisibleHint():" + getUserVisibleHint());
             super.onStart();
             if(isInit&&!isStart&&getUserVisibleHint())
             {
                isStart=true;
                onFragmentStartLazy();
             }
       }
    //当Fragment被滑到可见的位置时,调用
    protected void onFragmentStartLazy() {
        Log.d("TAG", "onFragmentStartLazy() called with: " + "");
    }

        @override
        public final void onStop()
        {
           super.onStop();
           if(isInit&&isStart&&getUserVisibleHint())
           {
              isStart=false;
              onFragmentStopLazy();
           }
        }
         @Override
    @Deprecated
    public final void onResume() {
        Log.d("TAG", "onResume() : " + "getUserVisibleHint():" + getUserVisibleHint());
        super.onResume();
        if (isInit) {
            onResumeLazy();
        }
    }
     @Override
    @Deprecated
    public final void onResume() {
        Log.d("TAG", "onResume() : " + "getUserVisibleHint():" + getUserVisibleHint());
        super.onResume();
        if (isInit) {
            onResumeLazy();
        }
    }

    @Override
    @Deprecated
    public final void onPause() {
        Log.d("TAG", "onPause() : " + "getUserVisibleHint():" + getUserVisibleHint());
        super.onPause();
        if (isInit) {
            onPauseLazy();
        }
    }
     @Override
    @Deprecated
    public final void onDestroyView() {
        Log.d("TAG", "onDestroyView() : " + "getUserVisibleHint():" + getUserVisibleHint());
        super.onDestroyView();
        if (isInit) {
            onDestroyViewLazy();
        }
        isInit = false;
    }

     //当Fragment被滑到不可见的位置,offScreen时,调用
    protected void onFragmentStopLazy() {
        Log.d("TAG", "onFragmentStopLazy() called with: " + "");
    }

    protected void onCreateViewLazy(Bundle savedInstanceState) {
        Log.d("TAG", "onCreateViewLazy() called with: " + "savedInstanceState = [" + savedInstanceState + "]");
    }

    protected void onResumeLazy() {
        Log.d("TAG", "onResumeLazy() called with: " + "");
    }

    protected void onPauseLazy() {
        Log.d("TAG", "onPauseLazy() called with: " + "");
    }

    protected void onDestroyViewLazy() {

    }



}

Basefragment的源码如下:

public class BaseFragment extends Fragment
{
    protected LayoutInflater inflater;
    private View contentView;
    private Context context;
    private ViewGroup container;
    @override 
    public void onCreate(Bundle savedInstanceState)
    {
       super.onCreate(savedInstanceState);
       context=getActivity().getApplicationContext();
    }
    //子类通过重写onCreateView,调用setContentView进行布局设置,否者contentView==null,返回Null
    @override
    public final View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState)
    {
       this.inflater=inflater;
       this.container=container;
       onCreateView(savedInstanceState);
       if(contentView==null)
          return super.onCreateView(inflater,container,savedInstanceState);
    return contentView;
    }
    protected void onCreateView(Bundle savedInstanceState)
    {

    }
    @override
    public void onDestroyView()
    {
       super.onDestroyView();
       contentView=null;
       container=null;
       inflater=null;
    }
    public Context getApplicationContex()
    {
       return context;
    }
    public void setContentView(int layoutResID)
    {
       setContetnView((ViewGroup)inflater.inflate(layoutResID,container,false));
    }
    public void setContentView(View view)
    {
       contentView=view;
    }
    public void getContentView()
    {
      return contentView;
    }
    public View findViewById(int id)
    {
       if(contentView!=null)
       {
          return contentView.findViewById(id);
       }
       return null;
    }
     // http://stackoverflow.com/questions/15207305/getting-the-error-java-lang-illegalstateexception-activity-has-been-destroyed
    @Override
    public void onDetach() {
        Log.d("TAG", "onDetach() : ");
        super.onDetach();
        try {
            Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
            childFragmentManager.setAccessible(true);
            childFragmentManager.set(this, null);

        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void onDestroy() {
        Log.d("TAG", "onDestroy() : ");
        super.onDestroy();
    }

}

亲测有效
备注:转载地址 (http://www.jianshu.com/p/8a772b9df6d5)

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值