问题
I have a couple of CheckBoxPreferences
set up, my preference class extends PreferenceActivity
and implements OnSharedPreferenceChangeListener
This is what I'm using to respond to people checking/unchecking the CheckBoxPreferences
:
public void onSharedPreferenceChanged(SharedPreferences P, String K) {
if (K.equals(CheckBoxPref_KEY_HERE)) {
MyClass.BooleanVariable = P.getBoolean("CheckBoxPref_KEY_HERE", true);
}
}
As far as I can tell, the onSharedPreferenceChanged
method above is never even getting called?
回答1:
checkBoxPreference = (CheckBoxPreference) this.findPreference("CheckBoxPref_KEY_HERE");
checkBoxPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
// do your work here
return true;
}
});
回答2:
Here is the soln if you want to do something on all the preferences:
Create a class member:
SharedPreferences settings;
in your onCreate method:
settings = getSharedPreferences(<your_pref_name>, 0);
settings.registerOnSharedPreferenceChangeListener(new SharedPreferences.OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged (SharedPreferences sharedPreferences, String key) {
// Do whatever
}
});
来源:https://stackoverflow.com/questions/8373131/checkboxpreference-onsharedpreferencechanged-method-not-getting-called