Lazy loading of Fragment data

Posted by nickadeemus2002 on Fri, 01 May 2020 13:46:07 +0200

  • The usage scenario of Fragment lazy loading is that when a ViewPager manages multiple fragments, the "excellent" cache mechanism of ViewPager will display a Fragment and pre load some resources of two adjacent fragments (which will trigger the onCreate life cycle of adjacent fragments). Lazy loading allows us to load data only when Fragment is visible, which can save unnecessary overhead.
  • Look at the name "lazy load". In fact, it is the setUserVisibleHint(boolean isVisibleToUser) method provided by the system to load data.
  • setUserVisibleHint:

Set a hint to the system about whether this fragment's UI is currently visible to the user.
An app may set this to false to indicate that the fragment's UI is scrolled out of visibility
or is otherwise not directly visible to the user.
This may be used by the system to prioritize operations such as fragment lifecycle updates
or loader ordering behavior.

 * Lazy loading Fragment
public abstract class BasePageFragment extends BaseFragment {

    protected boolean isViewInitiated;
    protected boolean isVisibleToUser;
    protected boolean isDataInitiated;

    public void onCreate(Bundle savedInstanceState) {

    public void onActivityCreated(Bundle savedInstanceState) {
        isViewInitiated = true;

    public void setUserVisibleHint(boolean isVisibleToUser) {
        this.isVisibleToUser = isVisibleToUser;

    public abstract void fetchData();

    public boolean prepareFetchData() {
        return prepareFetchData(false);

    public boolean prepareFetchData(boolean forceUpdate) {
        if (isVisibleToUser && isViewInitiated && (!isDataInitiated || forceUpdate)) {
            isDataInitiated = true;
            return true;
        return false;


Topics: Fragment