Prevent ViewPager from destroying off-screen views

By default, ViewPager recreates the fragments when you swipe the page. To prevent this, you can try one of two things:

1. In the onCreate() of your fragments, call setRetainInstance(true).

2. If the number of fragments is fixed & relatively small, then in your onCreate() add the following code:

ViewPager mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setOffscreenPageLimit(3);

If I remember correctly, the second option is more promising. But I urge you to try both and see which of them work.


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);