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

前端 未结 14 1139
感动是毒
感动是毒 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 04:04

    There is no need to do those extra coding, i have faced this problem and solved it by a single line.

    After many hours looking on all the answers in this and other similar questions, i found out very easiest way to do this without extending ListPreference, you can do it in common extends PreferenceActivity, see the code bellow.

    public class UserSettingsActivity extends PreferenceActivity 
    {
        ListPreference listpref;
    
        @Override
        public void onCreate(Bundle savedInstenceState)
        {
            super.onCreate(savedInstenceState);
            addPreferencesFromResource(R.xml.settings);
            listpref = (ListPreference)findPreference("prefDefaultCurrency");
    
            listpref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() 
            {           
                @Override
                public boolean onPreferenceChange(Preference preference, Object value) {
                // TODO Auto-generated method stub
    
                listpref.setSummary(listpref.getEntries()[Integer.parseInt(value.toString())]);
                return true;
            }
        });
    

    Thats it, with a single line, all you have to do is get value passed from the onPreferenceChange(Preference preference, Object value) parse it to integer and pass it to listpref.setSummary(listpref.getEntries()[Integer.parseInt(value.toString())]);

提交回复
热议问题