[Android] – How to solve Fragment in ViewPager not restored after popBackStack ?>

[Android] – How to solve Fragment in ViewPager not restored after popBackStack

Problem

 

A Fragment is not reattached to its hosting ViewPager after returning from another fragment.

Situation

One Activity hosting a Fragment whoselayout holds a ViewPager. The ViewPager is populated by a FragmentStateViewPagerAdapter. The single Fragments hosted inside the pager (PageFragment for example) can open sub page lists, containing a new set of pages.

Behaviour

Everythings will work fine, but when user use the Back Button while transition to another fragment, it’ll be blank instead of load all item of the ViewPager.

The idea

When we create the Adapter for the ViewPager, we must provide a FragmentManger to the Adapter (for create the Fragment inside ViewPager), we should do this:

instead of use the:

we should use this:

What’s different here? Yes, at you can see, the stack of our sample is: Activity > Fragment > ViewPager > Fragments (> mean contain), so at the ViewPager layer, if we use the getSupportFragmentManager(), it’ll useless, because it’s own by the Activity but the ViewPager is own by Fragment so the getChildFragmentManager() will be good here, because it’s child. That’s all!

Have fun!

Leave a Reply

Your email address will not be published. Required fields are marked *