ViewPager viewPager = findViewById(R.id.viewPager); viewPager.setOffscreenPageLimit(2);
import android.support.v4.view.ViewPager; public class MyFragmentPagerAdapter extends FragmentPagerAdapter { private static final int OFFSCREEN_PAGE_LIMIT = 3; public MyFragmentPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { // Return the Fragment for the given position } @Override public int getCount() { // Return the total number of pages } @Override public void destroyItem(ViewGroup container, int position, Object object) { // Override the default behavior to prevent destroying pages that are not offscreen if (position < getCount() - OFFSCREEN_PAGE_LIMIT || position > getCount() + OFFSCREEN_PAGE_LIMIT) { super.destroyItem(container, position, object); } } }This code is an example implementation of a custom FragmentPagerAdapter. The OFFSCREEN_PAGE_LIMIT constant is set to 3, and the destroyItem() method is overridden to prevent destroying pages that aren't offscreen. This helps to ensure that pages remain in memory as long as they're needed, without retaining too many pages at once. Package library: android.support.v4.view.