Search code examples
androidandroid-fragmentsandroid-viewpager

Is it ok to hold the list of fragments as a class reference in the class extending FragmentStatePagerAdapter


Is it ok to hold the list of fragments as a class reference in the class extending FragmentStatePagerAdapter as opposed to instantiating the fragment in getItem(int position) based on the position (which basically ensures that only 2 fragments are in memory, and whenever a fragment gets GC'ed invokes getItem again). For example my ViewPagerAdapter looks like below

public class ViewPagerAdapter extends FragmentStatePagerAdapter {
    List<? extends ViewPagerFragment> fragments;

    public ViewPagerAdapter(FragmentManager fm, List<? extends ViewPagerFragment> fragments) {
        super(fm);
        this.fragments = fragments;
    }

    @Override
    public Fragment getItem(int position) {
        return fragments.get(position);
    }

    @Override
    public int getCount() {
        return fragments.size();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return fragments.get(position).getPageTitle();
    }
}

Solution

  • 1. Its ok to hold Fragment objects as it may contain some objects(which is already fetched/created at first time).

    2. Default it holds 3 fragments in memory A [B C D] E (assuming you are at C Fragment)

    3. You can always use setOffscreenPageLimit(int)

    Set the number of pages that should be retained to either side of the current page in the view hierarchy in an idle state. Pages beyond this limit will be recreated from the adapter when needed.

    4. Never ever hold View Objects of that fragment.