Android how to stop refreshing Fragments on tab change

one has to instance the FragmentPagerAdapter first, then .getCount() will return a value -

while .getCount() - 1 should be set as the default off-screen limit:

TabsPagerAdapter adapter = new TabsPagerAdapter(getSupportFragmentManager());

/* the ViewPager requires a minimum of 1 as OffscreenPageLimit */
int limit = (adapter.getCount() > 1 ? adapter.getCount() - 1 : 1);

ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(limit);

By default, ViewPager recreates the fragments when you swipe the page. To prevent this, you can try one of three 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:

mViewPager = (ViewPager)findViewById(R.id.pager);
mViewPager.setOffscreenPageLimit(limit);         /* limit is a fixed integer*/

3. Use a FragmentPagerAdapter as part of your ViewPager.

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


you can handle view recreation by check if the view is null or not

public class FragmentExample extends Fragment {

    private View rootView;

    public FragmentExample() {}

@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {

    if (rootView == null) {

        rootView = inflater.inflate(R.layout.fragment_example_layout, container, false);

        // Initialise your layout here

    } else {
        ((ViewGroup) rootView.getParent()).removeView(rootView);
    }

    return rootView;
    }
}

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