Android – Prevent ViewPager from destroying off-screen views

androidandroid-fragmentsandroid-viewpager

I have a ViewPager hooked up to a FragmentPagerAdapter that's displaying three fragments. The ViewPager appears to destroy a hosted fragment's view when it is more than one swipe away from the current position.

These views are all simple lists and this optimization is completely unnecessary, so I'd like to disable it. It's causing some visual problems because the lists have layout animations applied to them and those animations are being replayed after they've been destroyed and recreated. It also shows the scrollbar intro animation each time (where the scrollbar is briefly visible to indicate that scrolling is possible) which can be distracting, and the user's current scroll position is lost in the process.

It also doesn't load the third fragment until the first swipe happens, which is problematic because each fragment handles its own service calls and I'd prefer to have all three fire off at the same time when the activity loads. Having the third service call delayed is less than ideal.

Is there any way to convince ViewPager to stop this behavior and just keep all my fragments in memory?

Best Answer

In revision 4 of the Support Package, a method was added to ViewPager which allows you to specify the number of offscreen pages to use, rather than the default which is 1.

In your case, you want to specify 2, so that when you are on the third page, the first one is not destroyed, and vice-versa.

mViewPager = (ViewPager)findViewById(R.id.pager);
mViewPager.setOffscreenPageLimit(2);
Related Topic