保存Activity狀態
09-15 11:09:56.002 5292-5292/com.example.li.restartactivity D/test: stop
當我們的activity開始Stop之前,系統會調用 onSaveInstanceState()
Activity可以用鍵值對的集合來保存狀態信息。這個方法會默認保存Activity視圖的狀態信息,如在 EditText 組件中的文本或 ListView 的滑動位置。
爲了給Activity保存額外的狀態信息,你必須實現onSaveInstanceState() 並增加key-value pairs到 Bundle 對象中,例如:
static final String STATE_SCORE = "playerScore";
static final String STATE_LEVEL = "playerLevel";
...
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
Caution: 必須要調用 onSaveInstanceState() 方法的父類實現,這樣默認的父類實現才能保存視圖狀態的信息。
---------------------------------------》
兩種恢復ancticvity的方法
1,
由於 onCreate() 方法會在第一次創建新的Activity實例與重新創建之前被Destory的實例時都被調用,我們必須在嘗試讀取 Bundle 對象前檢測它是否爲null。如果它爲null,系統則是創建一個新的Activity實例,而不是恢復之前被Destory的Activity。
下面是一個示例:演示在onCreate方法裏面恢復一些數據:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Always call the superclass first // Check whether we're recreating a previously destroyed instance if (savedInstanceState != null) { // Restore value of members from saved state mCurrentScore = savedInstanceState.getInt(STATE_SCORE); mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL); } else { // Probably initialize members with default values for a new instance } ... }
2,onRestoreInstanceState()方法會在 onStart() 方法之後執行. 系統僅僅會在存在需要恢復的狀態信息時纔會調用 onRestoreInstanceState() ,因此不需要檢查 Bundle 是否爲null。
public void onRestoreInstanceState(Bundle savedInstanceState) { // Always call the superclass so it can restore the view hierarchy super.onRestoreInstanceState(savedInstanceState); // Restore state members from saved instance mCurrentScore = savedInstanceState.getInt(STATE_SCORE); mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL); }
Caution: 與上面保存一樣,總是需要調用onRestoreInstanceState()方法的父類實現,這樣默認的父類實現才能保存視圖狀態的信息。
/*@Override protected void onRestoreInstanceState(Bundle savedInstanceState) { String text = savedInstanceState.getCharSequence(STORE).toString(); editText.setText(text);//因爲editeText跳轉到其他的Activty是沒有指定一個view所以會報空指正異常需要 //重寫指定一個view就可以了 editeText=(EditeText)findViewById(R.layout.text); editText.setText(Text); super.onRestoreInstanceState(savedInstanceState); }*/