In my Android app I use tabs with a FragmentStatePagerAdapter. I have many tabs, so it is a problem, that the FragmentStatePagerAdapter calls the onCreateView-method for all of them when the app starts. This is completely useless, because the method is called again, when I open a tab. Is there a way to prohibit that the onCreateView-method is called for all tabs at the beginning (It should only be called for the current tab and the tab left and right from it)?
1 Answers
that the FragmentStatePagerAdapter calls the onCreateView-method for all of them when the app starts
ViewPager
will load 2-3 pages when it handed its PagerAdapter
. Other pages will only be created when the user changes pages. ViewPager
itself ensures that there is a page to either side of the current page (except for either end of the range of pages).
This is completely useless, because the method is called again, when I open a tab
onCreateView()
will only be called when the fragment is created or when a configuration change occurs (e.g., screen rotation). FragmentStatePagerAdapter
only hold onto a certain number of pages, so if the user swipes around a lot, FragmentStatePagerAdapter
will discard existing fragments and, eventually, re-create them if the user returns to them in the future.
Is there a way to prohibit that the onCreateView-method is called for all tabs at the beginning
It already behaves this way by default.
For example, if you take this sample project, change it to use FragmentStatePagerAdapter
, and add Log.e()
calls to onCreateView()
of the EditorFragment
, you will see two onCreateView()
calls when the ViewPager
is initially displayed, plus an additional call on every swipe that requires a fragment instance to be created.

- 986,068
- 189
- 2,389
- 2,491