gpt4 book ai didi

android - 调用 activity.onSaveInstanceState() 后的 commit() fragment 事务

转载 作者:行者123 更新时间:2023-12-02 13:38:31 27 4
gpt4 key购买 nike

在我的应用程序中,我有一个 Activity持有 3 Fragments .第一次Activity已创建,Fragment 1被陈列。接下来,所有 FragmentTransaction 将在网络操作后执行。例如:Fragment 1有一个 button向服务器发出请求,当结果准备好时,Fragment 1使用 listener调用父级内部定义的方法 activity , 替换 fragment 1fragment 2 .
这工作正常,除非父 activity收到 callback在其状态被 onSaveInstanceState() 保存后.安 IllegalStateException被抛出。

我已经阅读了有关此问题的一些答案,例如 this post多亏了 this blog,我才明白为什么会发生这个异常。 .

我也举个例子,我发现here尝试解决问题。这篇文章建议始终检查 activity通话前正在运行 commit() .所以我声明了一个 Boolean父变量中的变量 activity我把它的值设为 falseonPause()并到 trueonResume() .

网络操作完成后调用的父 Activity 回调类似于这样的Kotlin代码,其中 next是替换号码fragment :

private fun changeFragment(next:Int){
// get the instance of the next fragment
val currentFragment = createFragment(next)
// do other stuff here

if(isRunning){
// prepare a replace fragment transaction and then commit

ft.commit()

}else{

// store this transaction to be executed when the activity state become running

}

}

这段代码运行良好,现在我没有收到 Exception不再,但我的问题是:有可能是 onSaveInstanceState()在我检查后调用 if(isRunning)在我打电话之前 ft.commit() ,以便 commit() 在保存 Activity 状态后发生,导致 IllegalStateException再次?

我不确定 onSaveInstanceState()可以打断我的 changeFragment()任何时间点的方法。是否可以?

如果可能性存在并且我的代码可能会在 if(isRunning) 之间中断和 ft.commit() , 我可以做什么?
添加 try{}catch(){} 可以解决像这样阻止?:
if(isRunning){
try{
ft.commit()
}catch(ie:IllegalStateException){
// store the transaction and execute it when the activity become running
}
}else{
// store the transaction and execute it when the activity become running
}

最佳答案

它有点晚了,但是从 API 26+ 开始,我们可以使用以下内容来检查我们是否需要执行正常提交或 commitAllowingStateLoss()。

getSupportFragmentManager().isStateSaved();

关于android - 调用 activity.onSaveInstanceState() 后的 commit() fragment 事务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50228131/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com