Vhalad
Vhalad

Reputation: 119

Android TabLayout keep all tabs in ViewPager memory except one

I have a TabLayout with 4 tabs, what I want is to keep the first 3 tabs on ViewPager memory and recreate the fragment in the 4th tab everytime this tab is selected, is this possible?

This is my adapter:

public class SectionsPagerAdapter extends FragmentPagerAdapter {
        private Fragment[] mFragments;

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
            mFragments = new Fragment[4];
            mFragments[0] = PlaceholderFragment.newInstance(0);
            mFragments[1] = PlaceholderFragment.newInstance(1);
            mFragments[2] = PlaceholderFragment.newInstance(2);
            mFragments[3] = PlaceholderFragment.newInstance(3);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments[position];
        }

        @Override
        public int getCount() {
            // Show 4 total pages.
            return 4;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return null;
                case 1:
                    return null;
                case 2:
                    return null;
                case 3:
                    return null;
            }
            return null;
        }
    }

Upvotes: 0

Views: 758

Answers (1)

May Rest in Peace
May Rest in Peace

Reputation: 2207

I know I am a little late to this.

You can use the offscreenPageLimit on the ViewPagerInstance to specify the amount of pages to keep alive on either side. The default value is 1 (Also the min value is 1. So you can't have every fragment recreated. IMHO this is probably done for smooth animations)

Check this documentation link for details offscreenPageLimit https://developer.android.com/reference/android/support/v4/view/ViewPager#setoffscreenpagelimit

As specified in the docs, be careful when tweaking this property. It can make the user experience better or worse based on how and where to use it.

Now for the second part of your question about recreating only a particular fragment. Check this documentation link https://developer.android.com/reference/android/support/v4/app/Fragment#setUserVisibleHint(boolean)

This basically should be called whenever your fragment is made visible to the user or not.

public class YourFragmentThatNeedsToBeRecreated extends Fragment {

  @Override
  public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) {
      // write your refresh logic here
    }
  }

Though you might face problems with this approach. It doesn't work perfectly for some reason (Insert a rant about fragments here). You can try attaching and detaching your fragment in the refresh logic. But I hope there's a cleaner solution for it.

Upvotes: 1

Related Questions