我正在为我的项目使用 ViewPager2。我需要在带有 viewpager2 的片段中使用嵌套片段。在我尝试在片段(不是嵌套的片段)之间导航之前,它就像魅力一样。
第一次在片段之间导航后,应用程序崩溃并出现下面解释的错误。
包含嵌套片段 OnCreateView 方法的片段:
View view = inflater.inflate(R.layout.orders_fragment, null);
ViewPager2 viewPager = view.findViewById(R.id.childViewPager);
TabLayout tabs = view.findViewById(R.id.tabs);
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(getChildFragmentManager(),getLifecycle());
viewPager.setAdapter(sectionsPagerAdapter);
TabLayoutMediator.TabConfigurationStrategy tabConfigurationStrategy = (tab, position) -> {
String[] order_activity_tabs = getResources().getStringArray(R.array.situations);
for (int i=0; i<order_activity_tabs.length; i++) {
if(i==position)
tab.setText(order_activity_tabs[i]);
}
};
TabLayoutMediator tabLayoutMediator = new TabLayoutMediator(tabs, viewPager, tabConfigurationStrategy);
tabLayoutMediator.attach();
return view;
当我返回包含嵌套片段的片段时,它会崩溃
java.lang.IllegalStateException: Fragment no longer exists for key f#0: unique id 4fbe17b8-5e22-4e07-a543-4a79445ad39c
at androidx.fragment.app.FragmentManagerImpl.getFragment(FragmentManagerImpl.java:365)
at androidx.viewpager2.adapter.FragmentStateAdapter.restoreState(FragmentStateAdapter.java:549)
at androidx.viewpager2.widget.ViewPager2.restorePendingState(ViewPager2.java:350)
at androidx.viewpager2.widget.ViewPager2.dispatchRestoreInstanceState(ViewPager2.java:375)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:4045)
at android.view.View.restoreHierarchyState(View.java:20253)
at androidx.fragment.app.Fragment.restoreViewState(Fragment.java:548)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:907)
at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303)
at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:439)
at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManagerImpl.java:2079)
FragmentStatePagerAdapter 有解决方案,但 FragmentStateAdapter 没有。而且因为我不能覆盖 FragmentStateAdapter 中的方法,所以实现这个解决方案是不可能的。
谢谢您阅读此篇。任何帮助表示赞赏。