片段中的 commit() 和 commitAllowingStateLoss() 有什么区别

2022-08-31 16:21:46

我在我的项目中使用了提交方法,该方法使用片段构建了它。

无论如何,有时我遇到错误,我找不到任何好的解决方案,但只是这种方法。我将提交函数更改为,但没有长时间使用它来测试,所以这个函数可以帮助我吗?主要问题是,和 之间有什么区别?IllegalStateException: Can not perform this action after onSaveInstanceStatecommitAllowingStateLoss()commitAllowingStateLoss()commit()commitAllowingStateLoss()


答案 1

和 之间只有一个区别:如果发生状态丢失,后者不会引发异常。除此之外,它们具有相同的行为。commit()commitAllowingStateLoss()

有关详细信息,请参阅有关此主题的博客文章


答案 2

commit():

计划此事务的提交。提交不会立即发生;它将被安排为主线程上的工作,以便在下次该线程准备就绪时完成。

commitAllowingStateLoss():

事务只能在其包含活动保存其状态之前使用此方法提交。如果在该点之后尝试提交,则将引发异常。这是因为如果需要从活动状态还原活动,则提交后的状态可能会丢失。请参阅 commitAllowingStateLoss() 了解丢失提交的情况。

如果你在 onSaveInstance() 之后执行 commit(),你会得到以下异常:

java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
    at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1341)
    at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1352)
    at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:595)
    at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:574)

推荐