How to Get Selected Text and Value Android ListPreference

前端 未结 5 1192
清歌不尽
清歌不尽 2020-12-10 01:23

The XML file of my ListPreference



        
相关标签:
5条回答
  • 2020-12-10 02:07

    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
    0 讨论(0)
  • 2020-12-10 02:16

    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.

    0 讨论(0)
  • 2020-12-10 02:18
    SharedPreferences Preference = PreferenceManager.getDefaultSharedPreferences(this); 
     Preference.getString("your list preference key","-1")
    
    0 讨论(0)
  • 2020-12-10 02:20

    in your PreferenceActivity do something like:

    ListPreference listPreference = (ListPreference) findPreference("lpBirim");
    CharSequence currText = listPreference.getEntry();
    String currValue = listPreference.getValue();
    
    0 讨论(0)
  • 2020-12-10 02:20

    You can use this snippet to get the value:

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

    Have look on the tutorial

    0 讨论(0)
提交回复
热议问题