package com.android.hello;import android.app.Activity;import android.os.Bundle;import android.widget.TextView;public class HelloAndroid extends Activity { private TextView mTextView = null; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState); mTextView = new TextView(this); if (savedInstanceState == null) mTextView.setText("Welcome to HelloAndroid!"); else mTextView.setText("Welcome back."); setContentView(mTextView); }code]我认为这对最简单的情况就足够了,但无论我如何离开应用程序,它总是会回应第一条信息。( R1 a6 Z* K3 X! ^- V
我相信解决方案就像覆盖一样onPause或者类似的东西一样简单,但我在文档中戳了大约30分钟,没有发现任何明显的东西。 ' O2 f% }2 } g
2 Z8 y1 m8 c' N* F
解决方案: 5 a- K4 W! v3 r$ m9 r
您需要覆盖onSaveInstanceState(Bundle savedInstanceState)并将要改变的应用程序状态值写入Bundle参数如下:[code]@Overridepublic void onSaveInstanceState(Bundle savedInstanceState) { super.onSaveInstanceState(savedInstanceState); // Save UI state changes to the savedInstanceState. // This bundle will be passed to onCreate if the process is // killed and restarted. savedInstanceState.putBoolean("MyBoolean",true); savedInstanceState.putDouble("myDouble",1.9); savedInstanceState.putInt("MyInt",1); savedInstanceState.putString("MyString","Welcome back to Android"); // etc.} ' b d8 i$ Z! X, w# p B
Bundle 本质上是一种存储 NVP(“名称-值对)映射的方式将传输到onCreate()您onRestoreInstanceState()从活动中提取值的位置如下: 5 g0 U p, p4 v1 f1 u2 b
@Overridepublic void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); // Restore UI state from the savedInstanceState. // This bundle has also been passed to onCreate. boolean myBoolean = savedInstanceState.getBoolean("MyBoolean"); double myDouble = savedInstanceState.getDouble("myDouble"); int myInt = savedInstanceState.getInt("MyInt"); String myString = savedInstanceState.getString("MyString");}$ P$ y2 [$ A7 M4 T$ i T
或者来自一个片段。$ P/ k" H7 A* Z9 O2 w
@Overridepublic void onViewStateRestored(@Nullable Bundle savedInstanceState) super.onViewStateRestored(savedInstanceState); // Restore UI state from the savedInstanceState. // This bundle has also been passed to onCreate. boolean myBoolean = savedInstanceState.getBoolean("MyBoolean"); double myDouble = savedInstanceState.getDouble("myDouble"); int myInt = savedInstanceState.getInt("MyInt"); String myString = savedInstanceState.getString("MyString");} 8 i2 |6 X; [ O- b' K) _