39

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);

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.

Thanks for any help.

4

2 回答 2

121

您是否尝试过使用:它的工作通过

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

在清单文件中?

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

如果你在 Activity 中写这个参数不需要处理,框架会处理剩下的事情。如果方向改变,它将保留屏幕或布局的状态。

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

另一种方式另一种方式

于 2015-08-29T07:58:04.210 回答
27

要保存您的变量或值,您应该使用 onSaveInstanceState(Bundle); 当方向改变时应该恢复值也应该使用 onRestoreInstanceState() ,但不是很常见。(onRestoreInstanceState()在 onStart() 之后调用,而 onCreate() 在onStart()之前调用。使用 put 方法将值存储在onSaveInstanceState()

protected void onSaveInstanceState(Bundle icicle) {
  super.onSaveInstanceState(icicle);
  icicle.putLong("param", value);
}

并恢复onCreate()中的值:

public void onCreate(Bundle icicle) {
  if (icicle != null){
    value = icicle.getLong("param");
  }
}
于 2015-08-29T07:59:25.560 回答