Android listpreference - fetching value

不问归期 提交于 2019-12-24 03:30:57

问题


I have a listpreference. No matter how I copy the code here, it appears wrong, so I just copy the matter of it:

string-array name="listArray"
items: Mercedes, Audi, Porsche

string-array name="listValues"
items: car1, car2, car3

I have this code in the preferences.xml at the listpreference part:

 <ListPreference
          android:title="List Preference"
          android:summary="This preference allows to select an item in a array"
          android:key="listPref"
          android:defaultValue="digiGreen"
          android:entries="@array/listArray"
          android:entryValues="@array/listValues" />

And this is the code I want to fetch the selected item with:

   String listpref = preferences.getString("listPref", "n/a"); 
   Toast.makeText(TutorialPref.this, "Chosen item of ListPref:" + listpref, Toast.LENGTH_LONG).show();

Problem is, it returns the values not the items. So if I select Mercedes, the value I got is "car1".

How can I get "Mercedes"?


回答1:


You can create a map with your array values as keys and your array entries as values:

private Map<String,String> cars = new HashMap<String, String>();

 if (cars.isEmpty()) {
    String[] carNames = getResources().getStringArray(R.array.listArray);
    String[] carIds = getResources().getStringArray(R.array.listValues);
    for (int i = 0; i <  carIds.length; i++) {
    cars.put(carIds[i], carNames[i]);
    }
 }

And in your toast, retrieve the car name with cars.get(listpref)




回答2:


You just need to put the same array in the entryValues as in the entries

android:entryValues="@array/listArray"


来源:https://stackoverflow.com/questions/4761126/android-listpreference-fetching-value

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