简体   繁体   中英

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

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM