How to save the state of an Android CheckBox when the users exits the application?

☆樱花仙子☆ 提交于 2019-11-28 20:57:17

Combine onPause() and onResume() to save and load your CheckBox value.

Sample code:

@Override
public void onPause() {
    super.onPause();
    save(mCheckBox.isChecked());
}

@Override
public void onResume() {
    super.onResume();
    mCheckBox.setChecked(load());
}

private void save(final boolean isChecked) {
    SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putBoolean("check", isChecked);
    editor.commit();
}

private boolean load() { 
    SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
    return sharedPreferences.getBoolean("check", false);
}
wired00

i believe the google notepad3 tutorial explains about saving and restore state http://developer.android.com/resources/tutorials/notepad/notepad-ex3.html

save the state bundle in onSaveInstanceState() then get the bundle back in onStart()

Hope that helps

Edit: also check this one, its more concise. onSaveInstanceState () and onRestoreInstanceState ()

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!