Fragment懒加载类,本文的思路如下:
public abstract class LazyFragment extends Fragment {
// Whether load the data
protected boolean isLoadData = false;
// Whether finished load the data
public boolean isLoadDataFinished = false;
// Whether finish initial all views
public boolean isInitViewsFinished = false;
private View rootView = null;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
// Initial the root view, and repeat initial.
if (this.rootView == null) {
this.rootView = setRootView(inflater, container, savedInstanceState);
}
this.initAllViews(this.rootView);
this.isInitViewsFinished = true;
return this.rootView;
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
// When loading data
if(!this.isLoadData && isVisibleToUser) {
this.isLoadData = true;
this.lazyLoadData();
} else {
this.isLoadData = false;
this.lazyLoadState();
}
}
// Load the data
protected abstract void lazyLoadData();
// Set the root view
protected abstract View setRootView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState);
// Set initial all the views
protected abstract void initAllViews(View view);
// Set not visible
protected abstract void lazyLoadState();
}