fragments inside ViewPager2 are recreated when coming back to parent fragment

Viewed 340

I have a ViewPager2 in one of my fragments (let's call it fragment A). the viewpager uses a FragmentStateAdapter to create a number of fragments as the children (let's call these fragments children). when the user clicks on a button in fragment A, I replace it with fragment B.

now when the user clicks on device back button to come back to fragment A, I can see that children are automatically restored by the system (they are not shown in viewpager, but the onCreateView method of them are called and the saved bundle is delivered to them). how to avoid this behavior. I do not want children to be automatically recreated and restored.

2 Answers

In a nutshell, a ViewPager keeps an internal list of items (that respresent 'pages'). The number of items in this list is based on the the mOffScreenPageLimit value. By default it's set to 1, but you can change it by calling setOffscreenPageLimit(int limit). For example :

viewpager.offscreenPageLimit = 3

Try this in your onCreateView method:

if(view ==null)
{
       //your oncreate view code
 }
Related