从SharedPreferences存储和检索活动状态更改中的值

时间:2011-12-29 15:03:17

标签: android

基本上我有一个列表,我需要记住偏移并在每次恢复活动时加载偏移值,除非活动完全被破坏。

//Inside onCreate
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
Offset = settings.getInt("TheOffset", 0);
//End onCreate

@Override
protected void onPause() {
    super.onPause();
    SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
    SharedPreferences.Editor editor = settings.edit();
    editor.putInt("TheOffset", Offset);
}
@Override
protected void onStop() {
    super.onStop();
    SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
    SharedPreferences.Editor editor = settings.edit();
    editor.putInt("TheOffset", Offset);
}
@Override
protected void onDestroy() {
    super.onDestroy();
    //settings.getInt("TheOffset", 0);
    SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
    SharedPreferences.Editor editor = settings.edit();
    editor.putInt("TheOffset", 0);
}

2 个答案:

答案 0 :(得分:3)

onPause()将始终在您的活动被置于后台和/或销毁之前被调用,因此您不必在onStop()onDestroy()中保存状态。

对于要在SharedPreferences中保留的状态,您需要在写入值后添加editor.commit()。否则将不会存储。像这样:

super.onPause();
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("TheOffset", Offset);
editor.commit();

您可以在此处阅读更多内容:http://developer.android.com/reference/android/app/Activity.html#SavingPersistentState

答案 1 :(得分:0)

您只需要在onResume()中保存偏移量,并在活动将被销毁时将其设置为0,您可以在onPause()中使用isFinishing()来判断,如下所示:

protected void onPause() {
    if(isFinishing()) {
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putInt("TheOffset", 0);
        editor.commit();
    }
}

......但我仍然不知道你打算做什么。