I have an options menu with a checkbox. I can check and uncheck the checkbox when it has been clicked by the user which is fine. However, I am using SharedPreferences to store the value of this checkbox, so what I also need to do is to initialise the checkbox with whatever is stored in the SharedPreferences pref value i.e. if the pref is true/false, set the checkbox to checked/unchecked.
I guess I need to put some code inside my onCreateOptionsMenu, and I obviously need to use .setChecked(preference) to set the checkbox, but how do I programatically reference the checkbox itself?
The menu is created using:
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
return true;
}
The checkbox can be checked/unchecked using:
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.two_week:
if (item.isChecked()) {
item.setChecked(false);
}
else {
item.setChecked(true);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
I think the only method that you are missing is Menu’s findItem(). You can easily load any SharedPreferences (called
prefshere) like this: