I know that I can do something like this:
Preference pref = findPreference(getString(R.string.pref_vibrate_on_key));
pref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference,
Object newValue) {
LogUtil.d("Working!");
return true;
}
});
But I would like to add a Listener to every preference. I tried doing:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
sp.registerOnSharedPreferenceChangeListener(new OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(
SharedPreferences sharedPreferences, String key) {
LogUtil.d("working!");
}
});
but it doesn't work. Is this possible? If so, what am I doing wrong?
Assuming you want the same listener called each time, this might be a simpler solution:
Preference.OnPreferenceChangeListener changeListener = new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
// Code goes here
return true;
}
};
EditTextPreference pref = (EditTextPreference)findPreference(getString(R.string.pref1));
pref1.setOnPreferenceChangeListener(changeListener);
EditTextPreference pref2 = (EditTextPreference)findPreference(getString(R.string.pref2));
pref2.setOnPreferenceChangeListener(changeListener);
I think that onSharedPrefererenceChanged
is fired upon saving the preference (when you click BACK or HOME in PreferenceActivity
). I think that the easiest way is to create single class implementing OnPreferenceChangeListener
and switch through Preference.getKey();
and set it as OnPreferenceChangeListener
for each Preference.
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