在 Android 中,当屏幕方向改变(横向和纵向之间)时,会调用 onCreate
方法,如果处理不当,会在结果过于简单地改变布局时重新创建整个 Activity并保留所有相同的信息.
In Android, when the screen orientation changes (between landscape and portrait) the onCreate
method is called which ,if not handled properly, will recreate the entire activity when the result is too simply change the layout and retain all of the same information.
我知道一些解决此问题的方法,但我对最有效的方法感兴趣.
I know of a few ways to solve this, but I'm interested in the most efficient way.
1) 告诉清单我将通过覆盖 onConfigurationChanged()
方法并将其留空来处理方向更改.
1) Telling the manifest that I will handle the orientation change by overriding the onConfigurationChanged()
method and leaving it empty.
2) 覆盖 onSaveInstanceState()
并在此处保存数据以在 onCreate()
2) override onSaveInstanceState()
and save the data here to be repopulated in onCreate()
3) 覆盖 onPause()
将创建数据包并将其发送到 onSaveInstanceState()
3) Override onPause()
which will create a bundle of the data and send it to onSaveInstanceState()
显然,这些都是选项,但哪一个是更好的做法(小、中、大量数据)
Obviously, these are all options, but which one is a better practice (small, medium, large amounts of data)
谢谢
某些设备配置可能会在运行时更改(例如屏幕方向、键盘可用性和语言).当发生这种变化时,Android 会重新启动正在运行的 Activity(调用 onDestroy()
,然后调用 onCreate()
).
Some device configurations can change during runtime (such as screen orientation, keyboard availability, and language). When such a change occurs, Android restarts the running Activity (onDestroy()
is called, followed by onCreate()
).
onSaveInstanceState()
在它破坏你的活动,以便您可以保存有关应用程序状态的数据.你然后可以在 onCreate()
期间恢复状态或onRestoreInstanceState()
.onSaveInstanceState()
before it destroys your
activity so that you can save data about the application state. You
can then restore the state during onCreate()
or
onRestoreInstanceState()
.但是,您可能会遇到这样一种情况,即重新启动应用程序和恢复大量数据的成本可能会很高,并且会造成糟糕的用户体验.在这种情况下,您还有另外两个选择:
在配置更改期间保留对象
允许您的活动在配置更改时重新启动,但将有状态的对象携带到您的活动的新实例.
Allow your activity to restart when a configuration changes, but carry a stateful Object to the new instance of your activity.
自行处理配置更改
防止系统在某些配置更改期间重新启动您的 Activity,但在配置发生更改时接收回调,以便您可以根据需要手动更新您的 Activity.
Prevent the system from restarting your activity during certain configuration changes, but receive a callback when the configurations do change, so that you can manually update your activity as necessary.
因此,根据您对应用程序的数据操作和用户体验海岸,您可以选择最适合您的..
So, As per your data operation and coast of user experience with application you can choose what is best for you..
根据您只需要更改布局的需要,我认为您必须使用 onConfigurationChanged()
并在其中进行更改.
As per your need for just change the layout I think you have to use onConfigurationChanged()
and do the changes in it.
这篇关于Android:高效的屏幕旋转处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!