IllegalStateException: is not currently in the FragmentManager

后端 未结 12 2134
予麋鹿
予麋鹿 2021-01-31 08:40

I know it sounds like a duplicate of FragmentStatePagerAdapter IllegalStateException: is not currently in the FragmentManager but his solution isn\'t relevan

12条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-31 09:14

    Are you calling FragmentStatePagerAdapter.instantiateItem() from your own code? Generally, the ViewPager should be the only client that calls this method, however, it's easy to come across workarounds for other limitations that rely on this method.

    Due to the way FragmentStatePagerAdapter works, I would guess that the adapter has instantiated the Fragment, added it to it's internal collection of Fragments, and even began a transaction to add that Fragment to the FragmentManager, but that fragment transaction has not been committed or executed. This is exactly what instantiateItem() does when it hasn't already instantiated the requested Fragment.

    Another method, FragmentStatePagerAdapter.finishUpdate() is responsible for committing the transaction as well as for executing the pending transactions. finishUpdate() must be called after instantiateItem() or else the Fragment may not be added to the FragmentManager.

    Try something like this:

    // Get the current Fragment presented by the ViewPager.
    pagerAdapter.startUpdate(viewPager);
    Fragment fragment = pagerAdapter.instantiateItem(viewPager, viewPager.getCurrentItem());
    pagerAdapter.finishUpdate(viewPager);
    return fragment;
    

    startUpdate() has an empty implementation as of API level 19.

提交回复
热议问题