fragment 懒加载机制
1.首先要熟悉fragment的生命周期
如上图所示 当onattach调用时 fragment与activity发生绑定 如果此时你设置的
setOffscreenPageLimit()小于加入的fragment 后期会调用ondestroyView()方法
setUserVisibleHint()是先于任何fragment的生命周期的 并且会调用每个fragment的此方法 知道某个fragment显示后为true
当和viewpager绑定之后 会提前调用各个fragment的onattch oncraete oncraeteView onviewcreated等生命周期方法
附上basefragment代码
也就是第一次进来的时候 通过onviewcrated去加载数据 后面tab切换的时候都是通过setUserVisibleHint()来加载数据
public abstract class BaseFragment extends android.support.v4.app.Fragment { private Unbinder unbinder; private View mContextView = null; protected final String TAG = "BaseFragment"; protected boolean mIsVisible; protected boolean mHasLoaded; protected boolean mHasPrepare; @Override public void onCreate(@Nullable Bundle savedInstanceState) { LogUtils.d(TAG, "onCreate"); super.onCreate(savedInstanceState); // realm = Realm.getDefaultInstance(); } @Override public void onAttach(Context context) { super.onAttach(context); LogUtils.d(TAG, "onAttach"); } @Override public void onStart() { super.onStart(); LogUtils.d(TAG, "onStart"); } @Override public void onResume() { super.onResume(); LogUtils.d(TAG, "onResume"); } @Override public void onPause() { super.onPause(); LogUtils.d(TAG, "onPause"); } @Override public void onStop() { super.onStop(); LogUtils.d(TAG, "onStop"); } @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { LogUtils.d(TAG, "onCreateView"); mContextView = inflater.inflate(bindLayout(), container, false); unbinder = ButterKnife.bind(this, mContextView); initViews(mContextView); return mContextView; } @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); // LogUtils.d(TAG, "setUserVisibleHint: " + isVisibleToUser); mIsVisible = getUserVisibleHint(); lazyLoad(); } protected void lazyLoad() { // LogUtils.d(TAG, "lazyLoad: mIsVisible " + mIsVisible + " mHasLoaded " + mHasLoaded + " mHasPrepare " + mHasPrepare); if (!mIsVisible || mHasLoaded || !mHasPrepare) { return; } // LogUtils.d(TAG, "lazyLoad: load data in lazyLoad "); loadData(); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); LogUtils.d(TAG, "onViewCreated "); if (mIsVisible) { LogUtils.d(TAG, "onViewCreated: load data in #onViewCreated "); loadData(); } mHasPrepare = true; } protected abstract int bindLayout(); protected abstract void initViews(View mContextView); @Override public void onDetach() { super.onDetach(); LogUtils.d(TAG, "onDetach"); } @Override public void onDestroy() { LogUtils.d(TAG, "onDestroy"); super.onDestroy(); mHasLoaded = false; mHasPrepare = false; unbinder.unbind(); // realm.close(); } public void loadData(){ // LogUtils.d(TAG ,"-----loadData-----"); } @Override public void onDestroyView() { LogUtils.d(TAG, "onDestroyView"); super.onDestroyView(); } }