1.懒加载Fragment:
1 public abstract class LazyFragment extends Fragment { 2 boolean isViewPrepared; // 标识fragment视图已经初始化完毕 3 boolean hasFetchData; // 标识已经触发过懒加载数据 4 5 6 @Override 7 public void setUserVisibleHint(boolean isVisibleToUser) { 8 super.setUserVisibleHint(isVisibleToUser); 9 if (isVisibleToUser) {//当当前为显示页面时 10 lazyFetchDataIfPrepared(); 11 } 12 } 13 14 @Override 15 public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { 16 super.onViewCreated(view, savedInstanceState); 17 isViewPrepared = true; 18 } 19 20 @Override 21 public void onActivityCreated(@Nullable Bundle savedInstanceState) { 22 super.onActivityCreated(savedInstanceState); 23 lazyFetchDataIfPrepared(); 24 } 25 26 void lazyFetchDataIfPrepared() { 27 // 用户可见fragment && 没有加载过数据 && 视图已经准备完毕 28 if (getUserVisibleHint() && !hasFetchData && isViewPrepared) { 29 hasFetchData = true; //已加载过数据 30 lazyFetchData(); 31 } 32 } 33 34 //获得数据操作 35 abstract void lazyFetchData(); 36 }