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

时间:2015-01-12 03:19:10

标签: java android checkbox sharedpreferences

我要做的是在主菜单上按下按钮时设置菜单拉出(设置菜单是作为与我的主菜单独的活动实现的)。为简单起见,假设我的主菜单是空白的,只有一个按钮可以拉出设置菜单。在设置菜单中,有一个复选框和一个“完成”按钮,返回主活动。

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

一旦我获得了保存的复选框的信息,我如何能够从我的主要活动中访问此信息@我希望能够根据用户是否选中该框来运行某些代码?

我已经登陆并尝试了一些结果: 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),它没有改变任何东西(当设置菜单打开时仍然总是未选中)。发生了什么事?

2 个答案:

答案 0 :(得分:3)

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();
    }
}

答案 1 :(得分:0)

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

如果您正在使用onSaveInstanceState()您必须覆盖活动中的onRestoreInstanceState()函数或使用onCreate()中的已保存状态。我认为使用onRestoreInstanceState()会更好,这可以减少onCreate()中的代码,因为onSavedInstanceSate()只在系统调用时才会被调用 关闭应用程序以便为新应用程序运行腾出空间。如果您只想保存选中状态,请使用共享首选项,不需要onSaveInstanceState()。 //课堂上的decalre

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中保存状态,请将以下内容添加到您的活动中。

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

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

相关问题