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]我认为这对最简单的情况就足够了,但无论我如何离开应用程序,它总是会回应第一条信息。& g' M2 m5 I: R
我相信解决方案就像覆盖一样onPause或者类似的东西一样简单,但我在文档中戳了大约30分钟,没有发现任何明显的东西。0 I% I1 h- n f8 v0 H" s
- n' S& H, d1 V
解决方案: ' |. z7 R/ \: W/ V/ u, T: v
您需要覆盖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.} $ p7 n% N; U& m! k3 `
Bundle 本质上是一种存储 NVP(“名称-值对)映射的方式将传输到onCreate()您onRestoreInstanceState()从活动中提取值的位置如下: Q+ J& M& ?5 C; s
@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");}2 N9 C) C' @$ U3 u
或者来自一个片段。2 E' H2 K' G$ u! O$ ? O( }
@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");}+ o ^% q2 m4 W' H& p