ViewPager + fragment 中 懒加载的一点经验

来源:互联网 发布:淘宝营销推广方案 编辑:程序博客网 时间:2024/06/06 07:50

由于 viewpager 会预创建 page 页,所以当在fragment onCreatView 中进行一些业务时,体验会很差,比如网络请求等,此时需要考虑懒加载。下面是几个可能会遇到的问题:

  • 1.仅仅在setUserVisibleHint 方法中执行业务时,第一页,也就是第一个fragment不执行
    详细的说明可参考http://www.jianshu.com/p/ae3bf6fb2585和
    http://stackoverflow.com/questions/14731589/is-fragment-setuservisiblehint-called-by-the-android-system

  • 2.在setUserVisibleHint 和生命周期方法(如 onCreatView)均执行业务时,会导致重复加载

  • 针对 “点哪个加载哪个”我的解决方法

/** * this fragment will not preLoad by viewPager. * it would load data every time when we switch to this page. * you also set reload or not. * Created by Administrator on 2017/8/15. */public abstract class LazyLoadFragment extends Fragment {    protected BaseActivity context;    protected View savedView;    protected boolean isVisible = false, isPrepared = false, isloaded = false, reload = false;    public boolean isReload() {        return reload;    }    /**     *     * @param reload 可见时,是否重新 load     */    public void setReload(boolean reload) {        this.reload = reload;    }    @Override    public void onAttach(Context context) {        super.onAttach(context);        if (this.context == null) {            this.context = (BaseActivity) context;        }    }    @SuppressWarnings("deprecation")    @Override    public void onAttach(Activity activity) {        super.onAttach(activity);        if (this.context == null) {            this.context = (BaseActivity) activity;        }    }    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container,                             Bundle savedInstanceState) {        if (savedView != null) return savedView;        View view = inflater.inflate(R.layout.fragment_statistic_inspection, container, false);        ButterKnife.bind(this, view);        isPrepared = true;        savedView = view;        if (getUserVisibleHint()){            lazyLoad();            isloaded = true;        }        return savedView;    }    // This method may be called outside of the fragment lifecycle.    // and thus has no ordering guarantees with regard to fragment lifecycle method calls.    //note :会在onCreateView之前调用    @Override    public void setUserVisibleHint(boolean isVisibleToUser) {        super.setUserVisibleHint(isVisibleToUser);        if (isVisibleToUser && isPrepared) {            isVisible = true;            if (!isloaded || reload){                lazyLoad();                isloaded = true;            }        }    }    /**     * @return your fragment layout resource id .     */    protected abstract int setLayout();    /**     *     * put your load function here.     */    protected abstract void lazyLoad();}

参考:
1. https://stackoverflow.com/questions/10024739/how-to-determine-when-fragment-becomes-visible-in-viewpager
2. http://www.cnblogs.com/dasusu/p/5926731.html