Preload fragment's view in ViewPager on first run
Just call setOffscreenPageLimit()
in onCreate() (after initializing ViewPager). The OffscreenPageLimit sets the number of pages that should be retained to either side of the current page (in your case 2). With this all of your fragments will be instantiate.
(An other (highly recommended) possibility is to increase the performance of your lists or listadapters, because a loading time of 2 seconds doesn't sound good)
Related videos on Youtube
Duc Le
Updated on September 15, 2022Comments
-
Duc Le over 1 year
I'm using ViewPager that holds 3 fragments, each fragment loads a list. The problem is when the application runs for the first time and I swipe to the next fragment, this fragment needs sometime to load (about 2 seconds) before its view is visible. This is a very weird behavior. All I want is once the app has started, all fragments in ViewPager should be ready for user so when they swipe through fragments, there's no wait time. How can I do that?
-
MH. over 10 yearsActually setting it to
2
would already ensure all 3 fragments are kept around. The value sets the number of pages that should be retained to either side of the current page, not the total number of pages. -
Namenlos over 10 yearsYes, I know. But you can also set the limit to
100
and it still works ;-) This was just an example, of course he can set the limit to2
if he wants. -
MH. over 10 yearsWell in that case, why say "in your case 3" in your answer? That's not correct, and it signals to me that you did not know, which is why I originally added a comment to point that out.
-
Namenlos over 10 yearsOkay, to remove ambiguity about the
setOffscreenPageLimit()
function I will edit my answer.