I've got a ViewPager
with 4 tabs.
I'm using a custom adapter that extends FragmentPagerAdapter
.
The problem is that when I change the tab, the first Fragment
gets created again although it's not the currently visible.
Moreover, this only happens after changing the tab for the fourth time. E.g. tab1 -> tab2 -> tab3=> onStop
from tab1 is called. -> tab2 => onCreateView
from tab1 is called (onAttach
is not called).
I want to avoid this. I need all tabs to remain always in their state even when they are not currently displayed. How can I do this?
It's been as easy as using method setOffscreenPageLimit()
from ViewPager
.
More info: http://developer.android.com/reference/android/support/v4/view/ViewPager.html#setOffscreenPageLimit(int)
Viewpager has one public method named setOffScreenPageLimit which indicates the number of pages that will be retained to either side of the current page in the view hierarchy in an idle state.
Activity:
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
...
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = findViewById(R.id.container);
mViewPager.setOffscreenPageLimit(3); // change your number here
mViewPager.setAdapter(mSectionsPagerAdapter);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With