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;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        isViewInitiated = true;
        prepareFetchData();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        this.isVisibleToUser = isVisibleToUser;
        prepareFetchData();
    }

    public abstract void fetchData();

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

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

}

Topics: Fragment