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.
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 .
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.
You can use startActivityForResult(or broadcast/receiver) to get the result from the activity. Then use adapter. notifyDataSetChanged to refresh the fragment.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With