I have a PreferenceScreen
containing only CheckBoxPreferences
(categories to select). I need an option to check/uncheck all of them. I have the following code that does the job but there is one problem: checkboxes on the screen are not updated - I'd need to call some invalidate on the view or something.
Here is my present code:
private void checkAll() {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = settings.edit();
@SuppressWarnings("unchecked")
Map<String, Boolean> categories = (Map<String, Boolean>) settings.getAll();
for(String s : categories.keySet()) {
editor.putBoolean(s, true);
}
editor.commit();
}
private void uncheckAll() {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = settings.edit();
@SuppressWarnings("unchecked")
Map<String, Boolean> categories = (Map<String, Boolean>) settings.getAll();
for(String s : categories.keySet()) {
editor.putBoolean(s, false);
}
editor.commit();
this.restart();
}
This code works fine but I'd need to refresh the view somehow to see the result imediatelly (not just after closing and re-starting the settings activity).
Thank You all for any advice!
That's because you're not actually grabbing the preference objects, just the actual values. Try this in your for loops:
boolean theValue = param;
for(String s : categories.keySet()) {
Preference pref = findPreference(s);
if (pref instanceof CheckBoxPreference) {
CheckBoxPreference check = (CheckBoxPreference)pref;
check.setChecked(theValue);
}
}
I think you can omit calling the editor and committing, as the setChecked() will do that for you.
Check this out as well.