Search code examples
androidandroid-fragmentsandroid-viewpager

Fragment re-created when change tab with ViewPager


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?


Solution

  • 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)