Change the summary of a ListPreference with the new value (Android)

前端 未结 14 1112
感动是毒
感动是毒 2020-12-30 03:01

How can I modify the summary of a ListPreference to the new \"Entry\" string selected by the user (not the entry value)

I suppouse its with setOnPreferenceChangeList

14条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-30 03:56

    I also faced this problem and I finally found a solution by using the value coming from the listener. In my example below (for a ListPreference), I first get the index of the value in the ListPreference array, then I retrieve the label of the value using this index:

    passwordFrequencyLP.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object newValue) {
                int newFrequency = Integer.valueOf(newValue.toString());
    
                prefs.edit().putInt("settings_key_password_frequency", newFrequency).commit();
    
                //get the index of the new value selected in the ListPreference array
                int index = passwordFrequencyLP.findIndexOfValue(String.valueOf(newValue));
                //get the label of the new value selected
                String label = (String) passwordFrequencyLP.getEntries()[index];
    
                passwordFrequencyLP.setSummary(label);
    
                makeToast(getResources().getString(R.string.password_frequency_saved));
                return true;
            }
        });
    

    This little trick works well, I found many different possible solutions to this problem but only this one worked for me.

提交回复
热议问题