Get Key, not value, of the ListPreference selection - Possible?

隐身守侯 提交于 2019-12-05 15:05:50

A bit of a guess:

int index = mylistpreference.findIndexOfValue(selected)  // <- selected taken from your code above
String entry = mylistpreference.getEntries()[index];

just use:

mylistpreference.getEntry()

to get mylistpreference use:

mylistpreference= (ListPreference) getPreferenceScreen().findPreference(key);

key is the android:key you defined in preference.xml inside < ListPreference> tag.

The function is defined as

SharedPreferences.getString(String key, String defaultValue);

So in your example code, getString(R.string.select_string) would return the key.

When you add the SharedPreference, you need to specify the key, so the key would be the same one you used to set the value.

Edit:

using SharedPreferences.getString() with the ListPreference key as the key will return the value the user selected from the list. You don't need to create keys for each option in the ListPreference array, and these keys aren't created automatically. Use case statements that correlate to the ListPreference's entryValues.

@shai Your method lags to last selected entry

listPreference.getEntry()

Rather @Erik 's method works nicely

int index = listPreference.findIndexOfValue((String) value)
String entry = listpreference.getEntries()[index];

To properly update the summary of a ListPreference (using the label, instead of the key).

   @Override
    public boolean onPreferenceChange(Preference preference, Object value) {
        String stringValue = value.toString();

        if (preference instanceof ListPreference) {
            ListPreference listPreference = (ListPreference) preference;
            int prefIndex = listPreference.findIndexOfValue(stringValue);
            if (prefIndex >= 0) {
                CharSequence[] labels = listPreference.getEntries();
                preference.setSummary(labels[prefIndex]);
            }
        } else {
            preference.setSummary(stringValue);
        }
        return true;

    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!