I want to understand this exception in order to implement a proper fix.
There\'s a ViewPager and it uses a FragmentStatePagerAdapter to instantiate 2 fragments via g
This could help -
@Override
public Parcelable saveState() {
return null;
}
Add the line above in FragmentStatePagerAdapter
.
very good ! Since is repeat pager.setAdapter(adapter);
when call restoreState
cause exception:
Fragment no longer exists for key f0: index 0
we can Release Fragment RootView
public void onDestroyView() {
super.onDestroyView();
if (isRecyclerRootViewAlways()) {
mRootView = null;//<--
}
mMyFragmentLifecycle.onFragmentDestroyView(this);
}
if you are using ViewPager2 then use this method on ViewPager2 object
viewPager2.setSaveEnabled(false);
If you don't want the fragments to get reclaimed when they are offscreen, you should be using FragmentPagerAdapter
and not FragmentStatePagerAdapter
.
I have struggle on this problem for whole day, but now I found the solution.
private ViewPager _mViewPager;
_mViewPager.setOffscreenPageLimit(5);
//5 is how much page you have.
setOffscreenPageLimit
Set the number of pages that should be retained to either side of the current page in the view hierarchy in an idle state. Pages beyond this limit will be recreated from the adapter when needed.
Use Activity lifeCycle instead of Fragment.
public class MyAdapter extends FragmentStateAdapter {
public MyAdapter (@NonNull Fragment fragment) {
super(fragment.getFragmentManager(), fragment.getActivity().getLifecycle());
}
}
Or as others mentioned disable the ViewPager2
save state.
android:saveEnabled="false"
viewPager.setSaveEnabled(false);
viewPager.setSaveFromParentEnabled(false);