我在 firebase Crashlytics 上遇到非致命异常:
Non-fatal Exception: java.lang.IllegalStateException
Fragment already added
这是我的相关代码:
var isFragmentAdded = false
for (supportFragment in supportFragmentManager.fragments) {
if (supportFragment::class == fragment::class) isFragmentAdded = true
}
if (isFragmentAdded || fragment.isAdded) {
transaction.show(fragment)
} else {
transaction.add(R.id.contentFragment, fragment)
}
transaction.commitAllowingStateLoss()
正如你所看到的,我在添加 fragment 之前检查 fragment 是否以两种方式添加。为什么会出现这个问题呢? (我无法在我的设备或模拟器上重现它)
最佳答案
是的,我们的 crashlytics 日志中也有同样的异常。有几种可能的方法可以解决这个问题。
1.
所以在大多数情况下是因为commitAllowingStateLoss()
。这不仅仅是因为文档中所说的在交易期间“保存了状态”。它将使用之前的状态重新创建 Fragment
,根据我们的经验,它与流程或 Fragment
事务直接相关。
所以首先。删除它的使用,并修复您的事务状态设置。您不想在 fragment 可能位于堆栈中并且希望重用它的地方使用 commitAllowingStateLoss()
。 (就像上面的代码 fragment 一样)。
2.
我很确定您的问题是由上述第 1 点引起的。然而还有另一个原因,评论中已经提到了。 FragmentTransactions
是异步提交的。因此,您需要调用 executePendingTransactions()
有关更多信息,请参阅 here .
关于android - IllegalStateException fragment 已添加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64116300/