Preload fragment's view in ViewPager on first run

19,184

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)

Share:
19,184

Related videos on Youtube

Duc Le
Author by

Duc Le

Updated on September 15, 2022

Comments

  • Duc Le
    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.
    MH. over 10 years
    Actually 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
    Namenlos over 10 years
    Yes, 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 to 2 if he wants.
  • MH.
    MH. over 10 years
    Well 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
    Namenlos over 10 years
    Okay, to remove ambiguity about the setOffscreenPageLimit() function I will edit my answer.