How does setOffscreenPageLimit() improve ViewPager performance by retaining more offscreen Fragments?
When you use the default implementation of setOffscreenPageLimit()
it is only loading the one fragment which is to the right of it. For eg. when you are on index 1, it has index 2 loaded in memory but not index 0, so swiping left will have to generate a new fragment from scratch. To test this theory you might want to use setOffscreenPageLimit(2)
and then try swiping index 1->0. This in no way is the optimal solution but will help clear out your doubts about the concept.
Comments
-
Matt Logan almost 2 years
I have a
ViewPager
controlling fiveFragments
. When I swipe fromFragment
at index 1 toFragment
at index 0, there's a brief pause in the animation that I'd like to eliminate.Currently, I'm not calling
setOffscreenPageLimit()
, so I know thatFragment
0 is being held in memory by theViewPager
while I'm onFragment
1 in its idle state, because the off screen page limit defaults to 1 (one on either side of the currentFragment
).Here's where it gets confusing. If I call
setOffscreenPageLimit(4)
on myViewPager
, the pause in the swipe from 1 to 0 animation is gone -- the animation is smooth.Therefore, I conclude that somehow, keeping
Fragments
2-4 in memory improves the animation fromFragment
1 toFragment
0.How does retaining
Fragments
2-4 improve the swiping animation fromFragment
1 toFragment
0?Edit
I ran TraceView, using
onPageScrollStateChanged(int state)
to determine when to start and stop the trace, as follows:@Override public void onPageScrollStateChanged(int state) { if (state == 1 && mViewPager.getCurrentItem() == 1) { Debug.startMethodTracing("ViewPagerTesting", 100000000); } if (state == 0 && mViewPager.getCurrentItem() == 0) { Debug.stopMethodTracing(); } }
It appears that the
ViewPager
's accessibility methods are causing the UI thread to freeze. When I callsetOffscreenPageLimit(4)
on the ViewPager, these accessibility methods are way down in the trace -- taking negligible time to finish.What's causing the delay?
-
Matt Logan over 10 yearsI did some thinking on my own after posting my question, and came to this conclusion as well. The processes started in
onResume()
in fragment 2 was blocking the UI thread. This is a bit counterintuitive -- my initial reaction was that the pausing of fragment 2 was causing the delay, not the resuming. -
Ignacio Garat over 10 years@Shakti Is there a way to set the fragment that goes offscreen? I have 3 fragments and the third one overlaps the second one after being called for first time, how can I avoid that?