How do you handle fragment transactions when the s

2020-04-03 01:47发布

My app has several fragments and activities. Over the course of the main parent activity's lifecycle, the app presents information/options to the user in other activities.

The documentation for Fragments has the following stipulation for commit():

Caution: You can commit a transaction using commit() only prior to the activity saving its state (when the user leaves the activity). If you attempt to commit after that point, an exception will be thrown. This is because the state after the commit can be lost if the activity needs to be restored. For situations in which its okay that you lose the commit, use commitAllowingStateLoss().

The issue is that after returning to the parent activity, I can no longer use FragmentTransactions which are integral to the way I have designed navigation in the app.

One solution I have thought of is to change my activities to fragments, however my app will also eventually use in-app billing which I believe will always start its own activity. This seems like a huge restriction - at some point in development I will end up having to display a separate activity.

I could probably get away with using commitAllowingStateLoss(), but I feel like I am missing a major concept in Android tablet app development. Is there a way to start activities then return to the parent activity (which manages fragments) without losing the ability to commit FragmentTransactions?

1条回答
淡お忘
2楼-- · 2020-04-03 02:38

You can commit fragment transactions again when your parent activity is resumed/started, even if it has been previous paused. The docs only mean that you cannot commit during the period of time where the activity is paused (and the state has been saved) and before it has been resumed again. If you return to your parent activity after visiting another activity, you are free to use fragment transactions again after Activity.onStart() has been called.

The reason for this restriction is that Android saves the state of fragments associated with an Activity during Activity.onSaveInstanceState(). If you try to make fragment transactions after this point, then you will be exposed to state loss if Android needs to recreate + restore that Activity (since the information it uses to recreate the Activity state was only the data that was captured in Activity.onSaveInstanceState()).

查看更多
登录 后发表回答