java.lang.IllegalStateException: Fragment no longer exists for key f1: index 3

后端 未结 8 502
一整个雨季
一整个雨季 2020-12-24 10:43

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

相关标签:
8条回答
  • 2020-12-24 10:52

    This could help -

    @Override
    public Parcelable saveState() {
        return null;
    }
    

    Add the line above in FragmentStatePagerAdapter.

    0 讨论(0)
  • 2020-12-24 10:55

    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);
    }
    
    0 讨论(0)
  • 2020-12-24 10:57

    if you are using ViewPager2 then use this method on ViewPager2 object

    viewPager2.setSaveEnabled(false);
    
    0 讨论(0)
  • 2020-12-24 11:03

    If you don't want the fragments to get reclaimed when they are offscreen, you should be using FragmentPagerAdapter and not FragmentStatePagerAdapter.

    0 讨论(0)
  • 2020-12-24 11:03

    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.

    0 讨论(0)
  • 2020-12-24 11:05

    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.

    • in Layout: android:saveEnabled="false"
    • in code:
      • viewPager.setSaveEnabled(false);
      • viewPager.setSaveFromParentEnabled(false);
    0 讨论(0)
提交回复
热议问题