How do I retain the state of my ViewPager in my TabLayout when I'm replacing a Fragment on top of it?

1k Views Asked by At

I have a single activity that uses a bunch of different Fragments. I have a TabContainer Fragment that holds a TabLayout which uses a ViewPager to handle tab navigation. Each Tab is its own Fragment.

In one of my tabs, I want to tap and place a fragment on top of my Tabbed fragment. This is meant to be a "details" sort of screen, so I don't want the tabs to be visible. I'm using this and it works as intended:

fragmentTransaction.replace(android.R.id.content, fragmentToDisplay).addToBackStack(null).commit();

Now, when I navigate back, the content in my tab is empty. The content in the tab directly next to that tab is also empty. When I navigate two tabs away, the content is recreated and the normal functionality returns. Why is content not being recreated on the tabs initially when I remove my "detail" fragment?

1

There are 1 best solutions below

0
On BEST ANSWER

It turns out that I was simply not passing the correct FragmentManager to the FragmentStatePagerAdapter.

I needed to call getChildFragmentManager() on the Fragment, not getSupportFragmentManager() on the activity.

Thanks to these two posts for the answer: Fragment in ViewPager not restored after popBackStack and: Replacing ViewPager with Fragment - Then Navigating Back