保存复选框的状态,然后加载它

Saving a checkbox's state, and then loading it

我想做的是在按下主菜单上的按钮时弹出设置菜单(设置菜单是作为与主菜单分开的 activity 实现的)。为简单起见,假设我的主菜单除了 1 个拉出设置菜单的按钮外是空白的。在设置菜单中,returns到主activity.

有一个复选框和一个按钮"Done"

如何保存和加载复选框(代码应该是什么,我应该把它放在哪里,为什么,等等)?我试过用谷歌搜索它,并试图复制结果,但我似乎无法得到它。到目前为止发生了 2 件事:没有保存任何东西,或者我的程序崩溃了。

一旦我保存了有关复选框的信息,我如何才能从我的主 activity @我希望能够 运行 某些代码基于用户是否选中此框?

我已经登陆并尝试过的一些结果: How to save the checkbox state? - android Saving Checkbox states

(请记住,我对此完全陌生)

public class Settings extends ActionBarActivity {

    private static final String SETTING_CHECK_BOX = "SETTINGS";
    private CheckBox cb;
    //char boxChecked = '0';
    @Override
    protected void onCreate(Bundle savedSettings) {
        super.onCreate(savedSettings);
        cb = (CheckBox) findViewById(R.id.checkBox);
        setContentView(R.layout.activity_settings);
        cb.setChecked(isCheckedSettingEnabled());
    }

    private void setCheckedSettingEnabled(boolean enabled) {
        PreferenceManager.getDefaultSharedPreferences(this).edit().putBoolean(SETTING_CHECK_BOX, enabled).apply();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_settings, menu);
        return true;
    }

    private boolean isCheckedSettingEnabled() {
        return PreferenceManager.getDefaultSharedPreferences(this).getBoolean(SETTING_CHECK_BOX, false);
    }

    public void onPause() {
        super.onPause();

        // Persist the setting. Could also do this with an OnCheckedChangeListener.
        setCheckedSettingEnabled(cb.isChecked());
    }

    public void clickedDone (View v) {
        SharedPreferences settings = getSharedPreferences("SETTINGS", 0);
        settings.edit().putBoolean("check",true).commit();
        finish();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

所以现在我的应用程序不再崩溃,但状态不会被记住(设置菜单打开时始终未选中)。我将 cb.setChecked(checkState) 更改为 cb.setChecked(TRUE),这并没有改变任何东西(打开设置菜单时仍然始终未选​​中)。怎么回事?

使用 onSaveInstanceState() 存储状态数据后,系统使用 onRestoreInstanceState(Bundle savedInstanceState) 重新创建状态。

如果您正在使用 onSaveInstanceState() 您必须覆盖 activity 中的函数 onRestoreInstanceState() 或使用 onCreate() 中的已保存状态。我觉得用onRestoreInstanceState()比较好,可以减少onCreate()中的代码,因为onSavedInstanceSate()只有在系统启动时才会调用 关闭应用程序以便为 运行 的新应用程序腾出空间。如果你只想保存选中状态,使用共享首选项,不需要 onSaveInstanceState()。 //在class

中贴花
private  CheckBox cb;
private SharedPreferences preferences ;
private SharedPreferences.Editor editor;
private boolean CHECKED_STATE;
    @Override
    protected void onCreate(Bundle savedSettings) {
        super.onCreate(savedSettings);
        setContentView(R.layout.activity_settings);
        preferences = getApplicationContext().getSharedPreferences("PROJECT_NAME",                 android.content.Context.MODE_PRIVATE);
        editor = preferences.edit();
        CHECKED_STATE = preferences.getBoolean("check", false);
        cb = (CheckBox) findViewById(R.id.checkBox);
        cb.setChecked(CHECKED_STATE);
        cb.setOnCheckedChangeListener(new OnCheckedChangeListener(){
         @Override
        public void onCheckedChanged(CompoundButton buttonView,
                boolean isChecked) {
          editor.putBoolean("check", isChecked);
          editor.commit();
         }
        });
    }

   this code saves the state on clicking the check box.

要使其在 Back Press 时保存状态,请将以下内容添加到您的 activity。

@Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
  editor.putBoolean("check", cb.isChecked());
              editor.commit();
}

有关保存实例状态的更多详细信息,请参阅this link

onSaveInstanceState() 仅用于持久化 Activity 实例 的数据。一旦 Activity 调用了 finish(),该状态就不再相关。您需要将设置写入持久存储。适合您情况的简单存储解决方案是 SharedPreferences.

public class Settings extends ActionBarActivity {
    // Create a constant for the setting that you're saving
    private static final String SETTING_CHECK_BOX = "checkbox_setting";

    private CheckBox mCheckBox;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);
        mCheckBox = (CheckBox) findViewById(R.id.checkBox);

        // Set the initial state of the check box based on saved value
        mCheckBox.setChecked(isCheckedSettingEnabled());
    }

    @Override
    public void onPause() {
        super.onPause();

        // Persist the setting. Could also do this with an OnCheckedChangeListener.
        setCheckedSettingEnabled(mCheckBox.isChecked());
    }

    /**
     * Returns true if the setting has been saved as enabled,
     * false by default
     */
    private boolean isCheckedSettingEnabled() {
        return PreferenceManager.getDefaultSharedPreferences(this)
                .getBoolean(SETTING_CHECK_BOX, false);
    }

    /**
     * Persists the new state of the setting
     * 
     * @param enabled the new state for the setting
     */
    private void setCheckedSettingEnabled(boolean enabled) {
        PreferenceManager.getDefaultSharedPreferences(this)
                .edit()
                .putBoolean(SETTING_CHECK_BOX, enabled)
                .apply();
    }
}