簡體   English   中英

如何保存視圖的 state 並在用戶返回時恢復它?

[英]how to save state of a View and restore it when the user comes back in?

我正在創建一個 Android 應用程序,我在其中與兩個不同的視圖進行交互,因此用戶可以通過單擊按鈕在它們之間切換。 請注意,我使用的是 setContentView 方法。 那么如何保存每個視圖的 state(包含 EditText、可以啟用/禁用的按鈕)並在用戶離開視圖並返回時恢復它?

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_layout1);
}


@Override
protected void onSaveInstanceState(Bundle State) {
    super.onSaveInstanceState(State);
    State.putCharSequence("key" , txt.getText());
}

(txt) 是一個編輯文本。

@Override
protected void onRestoreInstanceState(Bundle State) {
    super.onRestoreInstanceState(State);
    txt.setText(State.getCharSequence("key"));
}

public void method1(View view) {
    setContentView(R.layout.id1);
}

public void method2 (View v){
   setContentView(R.layout.id2); 
}

當用戶返回它時,我想恢復 layout1 的 state。

我推薦閱讀 Activity 生命周期,特別是關於保存和恢復 UI state 的部分,可以在這里找到。 基本上,您需要將 UI state 保存在onSaveInstanceState()中。

編輯:現在發生的是EditText值沒有保存,因為您首先調用super.onSaveInstanceState(state) 首先將EditText值保存到Bundle ,然后調用super.onSaveInstanceState(state)

@Override
protected void onSaveInstanceState(Bundle State) {
    State.putCharSequence("key" , txt.getText());
    super.onSaveInstanceState(State);
}

然后在您的onRestoreINstanceState上,您不必調用super ,您只需獲取保存的值並立即將其設置為您的EditText

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM