Android在方向更改时保存状态 [英] Android save state on orientation change

查看:97
本文介绍了Android在方向更改时保存状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Android应用程序,该应用程序维护有关行进距离,经过时间等的状态。当用户在Android调用onDestroy()时,可以方便地将该状态存储在一个对象中,并将对该对象的引用存储在Bundle中更改屏幕方向,然后在onCreate(Bundle savedBundle)中恢复状态。但是,我在屏幕上的Buttons和EditText对象中也有一些状态,我想通过屏幕方向保持该状态。例如,在onStart(Bundle savedBundle)中,我调用:

I've got an Android application which maintains state regarding distance traveled, time elapsed, etc. This state I can conveniently store in an object and store a reference to that object in the Bundle when Android calls onDestroy() when the user changes the screen orientation, then restore the state in onCreate(Bundle savedBundle). However, I also have some state in the Buttons and EditText objects on the screen that I want to persist through screen orientations. For example, in onStart(Bundle savedBundle) I call:

_timerButton.setBackgroundColor(Color.GREEN);
_pauseButton.setBackgroundColor(Color.YELLOW);
_pauseButton.setEnabled(false);

然后在应用程序的整个操作过程中,这些按钮的颜色/启用状态将被更改。是否有更方便的方法来持久保存用户界面项(EditText,Button对象等)的状态,而不必手动保存/恢复每个按钮的每个属性?必须在屏幕方向之间手动管理这种状态真的很笨拙。

Then throughout the operation of my app, the colors/enabled status of these buttons will be changed. Is there a more convenient way to persist the state of user interface items (EditText, Button objects, etc) without having to manually save/restore each attribute for each button? It feels really clumsy to have to manually manage this type of state in between screen orientations.

感谢您的帮助。

推荐答案

您尝试过使用它吗:

<activity name= ".YourActivity" android:configChanges="orientation|screenSize"/>

在清单文件中?

默认情况下不起作用,因为当您更改方向时,将再次调用 onCreate 并重新绘制视图。

It does not work by default because , when you change the orientation onCreate will be called again and it redraws your view.

如果您在Activity中无需处理此参数,则框架将处理其余工作。
如果更改方向,它将保留屏幕或布局的状态。

If you write this parameter no need to handle in Activity , the framework will take care of rest of things. It will retain the state of the screen or layout if orientation is changed.

注意如果您使用其他布局横向模式,通过添加这些参数,不会调用横向模式的布局。

NOTE If you are using a different layout for landscape mode , by adding these parameters the layout for landscape mode will not be called.

其他方式另一种方式

这篇关于Android在方向更改时保存状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆