其中活动方法被调用时,发生方向的改变?方向、发生、方法

2023-09-12 04:27:25 作者:战天傲刃

在生命周期的哪个方法被调用时,发生方向的改变? 我的应用程序执行 onResume()方法,或者重新加载整个活动,因为我设置一个布尔值来检查它是否是第一次运行与否。我读过 onConfigurationChanged()启动时的方向变化发生时,是真的吗? 如何来处理呢?

Which method of the lifecycle is called when orientation changes occur? My application executes the onResume() method or maybe reloads the whole activity because I've set one boolean to check whether it is first run or not. I've read onConfigurationChanged() starts when orientation change occur, is it true? How to handle this?

推荐答案

有趣的...

活动是开始恢复()是你在你的XML默认声明。

Activity is start on resume() is which you declare in your Xml by default.

和我发现的问题的答案在堆栈溢出是...

and as I found from question answer on stack overflow is...

===取向变化=== 的onSaveInstanceState 的onPause 的onStop 的onCreate ONSTART onRestoreInstanceState onResume

=== Orientation Change === onSaveInstanceState onPause onStop onCreate onStart onRestoreInstanceState onResume

===切换到活动2 === 的onSaveInstanceState 在onPause

=== Switch TO Activity 2 === onSaveInstanceState onPause

===方向变化,而在活动2 === 的onStop 的onCreate ONSTART

=== Orientation Change WHILE IN Activity 2 === onStop onCreate onStart

===切回程从活性2 === onResume

=== Switchback BACK FROM Activity2 === onResume

敢猜测,因为活动1被隐藏在旋转时,onRestoreInstanceState不叫,因为没有'查看'(即,它不能被视为/查看)。此外,它是完全有可能有2个完全不同的布局文件纵向/横向其中可能有不同的ID不同的UI元素。

'm guessing that because Activity 1 is hidden at the time of rotation, onRestoreInstanceState isn't called because there is no 'view' (i.e., it can't be seen/viewed). Also, it is entirely possible to have 2 completely different layout files for portrait/landscape which potentially have different UI elements with different IDs.

这样一来,我会说,如果你想使用捆绑的onSaveInstanceState中保存自己的数据,那么你需要添加额外的逻辑在你的onCreate(在活动1)来处理自己的数据有(以及因为有条件做在onRestoreInstanceState)。

As a result, I'd say if you want to use the Bundle in onSaveInstanceState to save your own data, then you need to add extra logic in your onCreate (in Activity 1) to process your own data there (as well as doing it conditionally in onRestoreInstanceState).

在特定的,你可以维护一个最后已知方向场,这样的onCreate知道它需要处理自己的数据,因为方向已经改变,而不是依赖于onRestoreInstanceState被调用。

In particular, you could maintain a 'last known' orientation field so that onCreate knows that it needs to process your own data because orientation has changed, rather than relying on onRestoreInstanceState being called.