Checkbox item state on menu android

混江龙づ霸主 提交于 2019-12-07 08:46:28

问题


How can I set initial value of checkbox item part of a menu? When I start an Activity I want to set a boolean value saved in Shared Preferences.

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".LoginActivity">
    <item
        android:id="@+id/checkbox"
        android:title="@string/checkbox"
        android:orderInCategory="10"
        android:showAsAction="never"
        android:visible="true"
        android:checkable="true"
        android:checked="true"/>
</menu>

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.login, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == R.id.checkbox){

        if(item.isChecked()){
            item.setChecked(false);
        }else{
            item.setChecked(true);
        }
        SharedPreferences.Editor editor = prefs.edit();
        editor.putBoolean(PrefsConsts.CHECKBOX,item.isChecked());
        editor.commit();

    }
    return true;
}

I can always know what was the value, but I don´t know how to set the new one.


回答1:


First of all, get rid of the checked value in the layout

    <item
        android:id="@+id/action_check"
        android:title="@string/action_check"
        android:orderInCategory="200"
        app:showAsAction="never"
        android:visible="true"
        android:checkable="true"/>

Now you can set it in the code:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    SharedPreferences settings = getSharedPreferences("settings", 0);
    boolean isChecked = settings.getBoolean("checkbox", false);
    MenuItem item = menu.findItem(R.id.action_check);
    item.setChecked(isChecked);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.action_check) {
        item.setChecked(!item.isChecked());
        SharedPreferences settings = getSharedPreferences("settings", 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putBoolean("checkbox", item.isChecked());
        editor.commit();
        return true;
    }
    return super.onOptionsItemSelected(item);
}


来源:https://stackoverflow.com/questions/29122447/checkbox-item-state-on-menu-android

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