[英]onResumeFragments() called after onSaveInstanceState()
My activity may show a DialogFragment
when it resumes. 我的活动可能会在恢复时显示DialogFragment
。 As suggested in this fragment transactions tutorial , I'm doing that in onResumeFragments()
to avoid the dreaded IllegalStateException: Can not perform this action after onSaveInstanceState
. 正如在这个片段事务教程中所建议的那样,我在onResumeFragments()
这样做,以避免可怕的IllegalStateException: Can not perform this action after onSaveInstanceState
。 For the most part, all is well. 在大多数情况下,一切都很好。
But my activity also has an OnSharedPreferenceChangeListener
that restarts the activity when a certain preference is changed. 但是我的活动还有一个OnSharedPreferenceChangeListener
,可以在更改某个首选项时重新启动活动。 The preference change that triggers the listener is caused by making a selection in a Spinner
. 触发侦听器的首选项更改是由在Spinner
进行选择引起的。 If the activity restarts itself by calling recreate()
, I get the IllegalStateException
. 如果活动通过调用recreate()
重新启动, IllegalStateException
得到IllegalStateException
。 But if the activity restarts itself like this, there's no problem: 但如果活动像这样重启,那就没问题了:
finish();
final Intent intent = new Intent(StartActivity.this, StartActivity.class);
startActivity(intent);
I'd prefer to use recreate()
because I want my instance state to be saved. 我更喜欢使用recreate()
因为我希望保存我的实例状态。 Why would this result in onResumeFragments()
being called after onSaveInstanceState()
? 为什么这会导致在onSaveInstanceState()
之后调用onResumeFragments()
onSaveInstanceState()
?
Well, I feel kind of dumb. 好吧,我觉得有点愚蠢。 I had a fragment that called setRetainInstance(true)
but cached a reference to its activity in onCreate(...)
instead of onActivityCreated(...)
. 我有一个名为setRetainInstance(true)
的片段,但在onCreate(...)
而不是onActivityCreated(...)
缓存了对其活动的引用。 The fragment was attempting to display a dialog using the old activity. 该片段试图使用旧活动显示对话框。 (To be more precise, the activity was indirectly calling a method on the fragment from onResumeFragments()
.) Pretty messy. (更确切地说,活动是从onResumeFragments()
间接调用片段上的方法。)相当混乱。 I should probably rethink the whole relationship between the fragment and the activity. 我应该重新思考片段和活动之间的整个关系。
Edit: I've since discovered another way this can happen that isn't my fault. 编辑:我已经发现了另一种可能发生的方式,这不是我的错。 If the lock screen is shown over a running activity, onSaveInstanceState()
is called. 如果锁定屏幕显示在正在运行的活动上,则调用onSaveInstanceState()
。 But when the lock screen is dismissed, onRestoreInstanceState()
is not called between onResume()
and onResumeFragments()
. 但是当解锁锁定屏幕时, onRestoreInstanceState()
onResume()
和onResumeFragments()
之间不会调用onRestoreInstanceState()
onResumeFragments()
。 This bug is at least five years old. 这个bug至少有五年了。 Thanks, Google. 谢谢,谷歌。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.