Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fragments inside ViewPager2 are recreated when coming back to parent fragment

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.

like image 905
Soheil Avatar asked Feb 08 '21 15:02

Soheil


People also ask

How does ViewPager2 work?

ViewPager2 uses FragmentStateAdapter objects as a supply for new pages to display, so the FragmentStateAdapter will use the fragment class that you created earlier. Create an activity that does the following things: Sets the content view to be the layout with the ViewPager2 .

What is ViewPager2 in android studio?

ViewPager2 supports paging through a modifiable collection of fragments, calling notifyDatasetChanged() to update the UI when the underlying collection changes. This means that your app can dynamically modify the fragment collection at runtime, and ViewPager2 will correctly display the modified collection.

How do I refresh Fragmentpageradapter?

You can use startActivityForResult(or broadcast/receiver) to get the result from the activity. Then use adapter. notifyDataSetChanged to refresh the fragment.


Video Answer


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
like image 127
Hossein Avatar answered Oct 22 '22 04:10

Hossein


Try this in your onCreateView method:

if(view ==null)
{
       //your oncreate view code
 }
like image 1
Danish Avatar answered Oct 22 '22 05:10

Danish