Change Preference Summary

I'm still looking for a way to change the ListPreference summary to match its current value. After some research, I managed to get (partially) a job:

ListPreference pref = (ListPreference) findPreference("Repeat_PREFS"); pref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object val) { ListPreference pref = (ListPreference) findPreference("Repeat_PREFS"); pref.setSummary(pref.getEntry()); return true; } }); 

The problem is that when I select a value for the first time, the summary changes to some other value or doesn't change at all. When I select the same value a second time, the summary is set correctly. What am I doing wrong?

+4
source share
2 answers

There is no way to activate behavior for preference. You need to call setSummary () with the value you want to set as a resume, for example. using the preference listener.

EDIT (after changing the question ...): Do not use Preference.OnPreferenceChangeListener , as it is called before the new value is saved (see http://developer.android.com/reference/android/preference/Preference.OnPreferenceChangeListener .html ). Therefore, the behavior of your first change depends on your preference value.

I recommend implementing OnSharedPreferenceChangeListener in PreferenceFragment or PreferenceActivity . (Remember to register and unregister the listener.) This listener is called after the change in preference has been completed. You should also set the default value in XML for preferences.

+5
source

SharedPreferences OnSharedPreferenceChangeListener alternative for legacy code (if you cannot update all listeners or don't want to mix SharedPreferences with settings):

Use Preference.OnPreferenceChangeListener, but do not use the preference.getEntry () function, which will return the old value. Instead, get the new value through the newValue parameter, get your index in the entryValues ​​array and get the record by index in the record array.

 public OnPreferenceChangeListener prefListener = new OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { //Do not use lp.getEntry(), as it returns the old preference value before being changed //Read entry corresponding to entryValue newValue. ListPreference lPref = (ListPreference)preference; String newEntry = (String) lPref.getEntries()[lPref.findIndexOfValue(newValue.toString())]; //Compose your summary as you need preference.setSummary( getResources().getString( R.string.myPref_summary, newEntry)); return true; //Persist new value } }; 

This, of course, is not suitable for performance, but until it runs many times, it may suit you.

+1
source

Source: https://habr.com/ru/post/1433773/


All Articles