Search code examples
androidandroid-fragmentsandroid-viewpagerandroid-orientationfragmentpageradapter

Viewpager with fragment pager adapter and Fragment - retainInstanceState recreates fragment on orientation change


When I use retainInstanceState(true) in fragment and use it with a FragmentPagerAdapter, the fragment is recreated. Which is not expected behaviour. What is a potential work around

I found a blog post which gives a solution not to use retainInstanceState which is not possible in my case


Solution

  • Turns out viewpager retains fragments and tries to find fragment with that id.

    First thing to do in Fragment's onCreate:

    setRetainInstance(true);
    

    In activity with tabs, Make sure you handle onSaveInstanceState correctly

    @Override
    public void onSaveInstanceState(bundle){
       super.onSaveInstanceState(bundle);
    }
    

    Even without saving viewpager id or reference to fragment as suggested in similar questions, the same fragment is reattached on orientation change