1. 程式人生 > >fragment 懶載入機制

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(); } }