什么时候可以安全地执行FragmentTransaction? [英] When is it safe to commit a FragmentTransaction?

查看:92
本文介绍了什么时候可以安全地执行FragmentTransaction?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据文档

只能在创建/提交碎片交易之前活动保存其状态.如果您尝试在之后进行交易Activity.onSaveInstanceState()(且在以下之前)Activity.onStart或Activity.onResume(),您将收到一个错误.

A fragment transaction can only be created/committed prior to an activity saving its state. If you try to commit a transaction after Activity.onSaveInstanceState() (and prior to a following Activity.onStart or Activity.onResume(), you will get an error.

我可以理解,Activity.onSaveInstanceState()之后,片段事务无法提交的第一部分,因为如果需要恢复活动,则提交后的状态可能会丢失.

I can understand that the first part that a fragment transaction can't committed after Activity.onSaveInstanceState(), because the state after the commit can be lost if the activity needs to be restored.

但是我不明白为什么我们不能在Activity.onStart或Activity.onResume()之前提交片段事务?()oncreate()也在Activity.onStart或Activity.onResume()之前.这是否意味着我们甚至不能在oncreate()中提交它?

But I don't understant why we can't commit a fragment transaction prior to a Activity.onStart or Activity.onResume()? Oncreate() is also prior to Activity.onStart or Activity.onResume().Does it mean that we can't even commit it in oncreate()?

推荐答案

此处的关键是,在调用 onSaveInstanceState() 之前和之后,您不能提交事务.以下 onStart() onResume().

The key here is that you can't commit a transaction after a call to onSaveInstanceState() and prior to a following onStart() or onResume().

您可以在初始的 onCreate()和后续的 onStart() onResume()上提交事务,因为没有状态.

You can commit transactions just fine on the initial onCreate() and a subsequent onStart() or onResume() because there is no state.

但是,如果活动正在恢复其状态(即先前曾调用过 onSaveInstanceState(),并且活动正在使用该状态重新创建自身,则无法执行Fragment事务.这是因为如果您在Activity恢复先前的Fragment状态之前提交Fragment事务,最终会导致您不清楚所处的状态.保存的状态是否优先于通过提交Fragment事务创建的新状态,还是应该使新事务优先于已保存状态?

However, if the Activity is restoring its state (i.e. onSaveInstanceState() was previously called, and the Activity is recreating itself with that state, you cannot perform a Fragment transaction. This is because if you commit a Fragment transaction prior to the Activity restoring the previous Fragment state, you end up in a situation where it is unclear what state you are in. Does the saved state take precedence over the new state that you have created by committing a Fragment transaction, or should the new transaction take precedence over the saved state?

检查这种情况的最简单方法是检查传递给 onCreate()和其他生命周期方法的 savedInstanceState 捆绑包是否为空.如果为空,则没有保存状态,您可以安全地执行交易.如果它不为null,则存在您可能想要保留的保存状态.

The easiest way to check for this scenario is to check if the savedInstanceState bundle passed to onCreate() and other lifecycle methods is null. If it's null, there is no saved state and you are safe to perform your transaction. If it is not null, then there is saved state that you probable want to preserve.

这篇关于什么时候可以安全地执行FragmentTransaction?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆