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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With