How to Get Selected Text and Value Android ListPre

2019-01-18 10:09发布

The XML file of my ListPreference

<ListPreference android:key="lpBirim" android:title="Birim"
        android:summary="" android:defaultValue="0"  android:persistent="false"/>

How to get the selected text and the selected value?

5条回答
一纸荒年 Trace。
2楼-- · 2019-01-18 10:39

You can use this snippet to get the value:

 SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); 
 sp.getString("lpBirim","-1")

Have look on the tutorial

查看更多
霸刀☆藐视天下
3楼-- · 2019-01-18 10:45

Here is an example:

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

    ListPreference listPreference = (ListPreference) preference;
    int index = listPreference.findIndexOfValue(textValue);

    CharSequence[] entries = listPreference.getEntries();

    if(index >= 0)
        Toast.makeText(preference.getContext(), entries[index], Toast.LENGTH_LONG);

    return true;
}
  • index contains the index of the clicked item
  • textValue is the Selected Value
  • entries[index] is the Selected Text
查看更多
别忘想泡老子
4楼-- · 2019-01-18 10:46

in your PreferenceActivity do something like:

ListPreference listPreference = (ListPreference) findPreference("lpBirim");
CharSequence currText = listPreference.getEntry();
String currValue = listPreference.getValue();
查看更多
再贱就再见
5楼-- · 2019-01-18 10:47

You can use findPreference() to get a ListPreference that has all methods you need. To have it working you need to use or extend PreferenceFragment first.

查看更多
一纸荒年 Trace。
6楼-- · 2019-01-18 10:49
SharedPreferences Preference = PreferenceManager.getDefaultSharedPreferences(this); 
 Preference.getString("your list preference key","-1")
查看更多
登录 后发表回答