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?
Asked
Active
Viewed 2.0k times
18
-
Are you using FragmentPageAdapter or FragmentStatePageAdapter? – Delyan Aug 20 '13 at 17:53
-
What you could consider doing is caching the fragment list adapters in the activity (or in the pager). That will prevent the adapters from being reloaded on each page change. – ahodder Aug 20 '13 at 18:15
-
@Delyan I use FragmentPagerAdapter – Duc Le Aug 20 '13 at 19:32
-
*"this fragment needs sometime to load (about 2 seconds) before its view is visible"* - that sounds like you should throw up a loading indicator to bridge the gap. Although, if something is blocking the UI thread during this 2 second delay, you should fix that in stead. The answer below won't really help in that case, since it just shifts the delay to when the `ViewPager` is created. – MH. Aug 20 '13 at 19:34
1 Answers
39
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)

Namenlos
- 1,615
- 2
- 18
- 24
-
2Actually 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. – MH. Aug 20 '13 at 19:31
-
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. – Namenlos Aug 20 '13 at 20:58
-
3Well 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. – MH. Aug 20 '13 at 21:05
-
1Okay, to remove ambiguity about the [`setOffscreenPageLimit()`](http://developer.android.com/reference/android/support/v4/view/ViewPager.html#setOffscreenPageLimit%28int%29) function I will edit my answer. – Namenlos Aug 20 '13 at 21:18