Using onCreate vs. onRestoreInstanceState

时间:2016-04-04 17:10:48

标签: android instance oncreate

Is there technically any reason why I should use onRestoreInstanceState? Could I not do all the restoration in onCreate by checking if the savedInstanceState bundle is null? What is the primary benefit of using onRestoreInstanceState over doing everything in onCreate?

3 个答案:

答案 0 :(得分:23)

onRestoreInstanceState

This method is called after onStart() when the activity is being re-initialized from a previously saved state, given here in savedInstanceState. Most implementations will simply use onCreate(Bundle) to restore their state, but it is sometimes convenient to do it here after all of the initialization has been done or to allow subclasses to decide whether to use your default implementation.

onRestoreInstanceState guarantees you receive a non-null Bundle object also in the lifecycle of activity it's called after onStart But onCreate: you should always check if the Bundle object is null or not to determine the configuration change and as you know it's called before onStart So It's all up to you and depends on your needs.

答案 1 :(得分:0)

大多数情况下,我倾向于使用onCreate(Bundle)还原活动状态,但是如果您要进行一些初始化,然后再还原状态,最好使用onRestoreInstanceState(),它通过子类提供了很大的灵活性来还原状态扩展当前活动。还要注意,onRestoreInstanceState()在onStart()之后调用,而onCreate(bundle)在此之前调用。

如果您有大量数据,则可以实现处理UI控制器逻辑的ViewModel类。 ViewModel对象会在配置更改期间自动保留,以便它们保存的数据可立即用于下一个活动或片段实例。例如,如果您需要在应用程序中显示用户列表,请确保分配职责以将用户列表获取并保留给ViewModel,而不是活动或片段。 它还提供去耦功能,并使您的活动或片段用于一个目的,而不是处理UI逻辑的过多责任。

答案 2 :(得分:0)

我认为我们可以看到此文档Restore activity UI state using saved instance state

这里有几点

1。onCreate()和onRestoreInstanceState()回调方法都接收包含实例状态信息的同一个Bundle。

2。您可以选择实现onRestoreInstanceState(),而不是在onCreate()期间恢复状态,系统在onStart()方法之后调用该方法。仅当存在要还原的保存状态时,系统才会调用onRestoreInstanceState(),因此您无需检查Bundle是否为空: