OnPreferenceChangeListener for every setting

2019-03-29 10:24发布

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?

2条回答
女痞
2楼-- · 2019-03-29 11:24

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);
查看更多
Fickle 薄情
3楼-- · 2019-03-29 11:28

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.

查看更多
登录 后发表回答