Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checkbox item state on menu android

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.

like image 987
Alfaplus Avatar asked Dec 02 '22 17:12

Alfaplus


1 Answers

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);
}
like image 189
dev.bmax Avatar answered Dec 05 '22 06:12

dev.bmax