How to Get Selected Text and Value Android ListPreference
Asked Answered
D

5

21

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?

Denunciate answered 27/5, 2011 at 7:7 Comment(0)
Q
42

in your PreferenceActivity do something like:

ListPreference listPreference = (ListPreference) findPreference("lpBirim");
CharSequence currText = listPreference.getEntry();
String currValue = listPreference.getValue();
Quadrisect answered 16/10, 2011 at 22:9 Comment(0)
H
20

You can use this snippet to get the value:

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

Have look on the tutorial

Horgan answered 27/5, 2011 at 7:22 Comment(1)
I get Selected value From this function newValue Field But How To Get Selected Text? public boolean onPreferenceChange(Preference preference, Object newValue)Denunciate
P
10

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
Printmaker answered 15/8, 2013 at 8:44 Comment(0)
C
3
SharedPreferences Preference = PreferenceManager.getDefaultSharedPreferences(this); 
 Preference.getString("your list preference key","-1")
Congener answered 1/2, 2018 at 6:28 Comment(0)
E
0

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.

Ess answered 27/10, 2016 at 9:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.