Android活动生命周期

时间:2017-06-08 08:58:40

标签: java android android-activity

我需要在关闭Activity后保存过滤器。我正在使用onSaveInstanceState()来实现它。

protected void onSaveInstanceState(Bundle savedInstanceState) {
    super.onSaveInstanceState(savedInstanceState);
    savedInstanceState.putInt("age", sbAge.getProgress());
    savedInstanceState.putInt("age", spMyStatus.getSelectedItemPosition());
    if(rbMaleMe.isChecked())
        savedInstanceState.putInt("sex", 1);
    else if(rbFemaleMe.isChecked())
        savedInstanceState.putInt("sex", 2);
}
`

onRestoreInstanceState()方法中:

protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    sbAge.setProgress(savedInstanceState.getInt("age"));
    spMyStatus.setSelection(savedInstanceState.getInt("status"));
    if(savedInstanceState.getInt("sex") == 1)
        rbMaleMe.isChecked();
    else if (savedInstanceState.getInt("sex") == 2)
        rbFemaleMe.isChecked();
}

onCreate()方法中:

if (savedInstanceState != null)
{
    savedInstanceState.getInt("age");
    savedInstanceState.getInt("sex");
    savedInstanceState.getInt("status");
}

但它不起作用。 当我关闭并重新启动活动时,只显示空视图。

onClick()

switch (v.getId()) { 
    case R.id.btnSaveInfo: 
        onStop(); 
        finish(); 
        break;
}

1 个答案:

答案 0 :(得分:0)

当操作系统杀死您的onSaveInstanceState()(例如回收资源)时,会调用

Activity。当您明确调用finish()时,将不会调用它。

如果您仍希望保留自己的值,可以使用SharedPreferences

(旁注,明确调用onStop()