問題

我一直在Android SDK平臺上工作,它有點不清楚如何儲存應用程式的狀態.所以鑑於’Hello,Android’示例的這個小型重新工具:

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

我認為對於最簡單的情況來說足夠了,但它總是響應第一條訊息,無論我如何從應用程式中導航.

我確信解決方案就像覆蓋onPause或類似的東西一樣簡單,但我已經在文件中刪除了30分鐘左右,並且沒有找到任何明顯的東西.

  最佳答案

您需要覆蓋onSaveInstanceState(Bundle savedInstanceState)並編寫您想要更改為Bundle引數的應用程式狀態值,如下所示:

 @Override
public 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.
}
 

Bundle基本上是儲存NVP(“Name-Value Pair”)對映的方法,它將傳遞給onCreate()onRestoreInstanceState(),然後提取這樣的值:

 @Override
public 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");
}
 

您通常會使用這種技術來儲存應用程式的例項值(選擇、未儲存的文字等)。

  相同標籤的其他問題

androidandroid-activityapplication-state