如何添加支票以防止出现此错误
我在此代码中收到错误:
private fun clearFragmentsFromContainer() {
if(supportFragmentManager.backStackEntryCount>0) {
supportFragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE)
}
}
在线错误:
supportFragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE)
日志:
java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:2080)
at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:2106)
at android.support.v4.app.FragmentManagerImpl.popBackStack(FragmentManager.java:832)
at com.caring2u.organizer.ui.activities.screen.ActSummaryEvent.clearFragmentsFromContainer(ActSummaryEvent.kt:524)
at com.caring2u.organizer.ui.activities.screen.ActSummaryEvent.onClickEventTabs(ActSummaryEvent.kt:466)
at com.caring2u.organizer.ui.activities.screen.ActSummaryEvent.dataEventsList(ActSummaryEvent.kt:162)
at com.caring2u.organizer.network.retrofit.retrofitTasks.RetroEventsSummary$initiate$1.onResponse(RetroEventsSummary.kt:62)
答案 0 :(得分:0)
您正尝试在onPause
之后更改片段堆栈,如从日志中可以看到的那样。
您可以使用FragmentManger.commitAllowingStateLoss
,也可以确保不要在onPause
之后调用此方法
答案 1 :(得分:0)
要删除容器中的所有碎片,请使用以下代码
for (Fragment fragment:getSupportFragmentManager().getFragments()) {
if (fragment instanceof NavigationDrawerFragment) {
continue;
}
else if (fragment!=null) {
getSupportFragmentManager().beginTransaction().remove(fragment).commit();
}
}
答案 2 :(得分:0)
您的分段事务可能正在 onSavedInstanceState()
回调之后提交。这意味着您的活动正在停止,并且正在以无法保存的状态添加片段。实际上,在onSavedInstanceState()调用期间,Android会为您的活动状态制作快照,这意味着,如果在状态保存后提交事务,则该事务将不会被记住,因为它从未被记录过。从用户的角度来看,这将导致UI状态丢失。
除了应该使用commitAllowingStateLoss
之外,您还应该了解是否要通过异步方法调用clearFragmentsFromContainer
方法,在这种情况下,您可能应该简单地将事务从async方法中移出。
有关“提交状态丢失”的更多信息:
为了了解您的活动是否已经调用过onSaveInstanceState()方法,您可能会考虑在onSaveInstanceState回调中放置一个标志,在双重方法onRestoreInstanceState中重置该标志,例如:
val saveInstanceStateCalled = false
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
saveInstanceStateCalled = true
}
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
saveInstanceStateCalled = false
}
然后您可以在调用clearFragmentsFromContainer
答案 3 :(得分:0)
我使用代码解决了此问题
if (!fragmentManager.isStateSaved()) {
if(supportFragmentManager.backStackEntryCount>0) {
fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE)
}
}