ViewPager懒加载

ViewPager是Android中常用的左右滑动控件

  • 懒加载定义:就是同一位置Fragment在ViewPager中处于可见时,保证当前可见页数据只加载一次
  • 关键方法:
 @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
        }
        TAG = mParam1;

        Log.e(TAG, "AAAA isVisibleToUser " + isVisibleToUser);
        super.setUserVisibleHint(isVisibleToUser);
    }
  • 关键基类Fragment
/**
 * -----------------------------------------------------------------
 * Copyright (C) 2014-2016, by com.trident, All rights reserved.
 * -----------------------------------------------------------------
 * 

* Author: aaron *

* Create: 2019/1/6 10:12 AM *

* Description: ViewPager懒加载基类 */ public abstract class BasePagerFragment extends Fragment { protected AppCompatActivity mActivity; // 控件是否初始化完成 protected boolean isViewInitiated; // 页面是否可见 protected boolean isVisibleToUser; // 数据是否加载 protected boolean isDataInitiated; // 每一次当前Fragment可见时,会调用该方法,并且isVisibleToUser字段会置为true, // 我们可以通过此字段判断当前Fragment是否可见; @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); this.isVisibleToUser = isVisibleToUser; // 当前可见时,我们尝试去加载数据 prepareFetchData(false); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); isViewInitiated = true; prepareFetchData(false); } public abstract void loadData(); protected void prepareFetchData(boolean forceUpdate) { // 由于setUserVisibleHint方法在onActivityCreated等方法之前调用,所以加载数据时机是不太合适的 // 所以最好是当前Fragment可见,并且当前Fragment中相关View控件都初始化ok时我们在调用数据请求刷新 // 通过isViewInitiated为true来判断View控件是否初始化成功 if (isVisibleToUser && isViewInitiated && (!isDataInitiated || forceUpdate)) { loadData(); isDataInitiated = true; } } }

你可能感兴趣的:(ViewPager懒加载)