Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OnPreferenceChangeListener for every setting

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?

like image 445
Macarse Avatar asked Feb 10 '10 16:02

Macarse


2 Answers

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);
like image 81
bugfixr Avatar answered Sep 18 '22 02:09

bugfixr


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.

like image 38
skyman Avatar answered Sep 22 '22 02:09

skyman