开发者

Android listpreference - fetching value

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 hav开发者_高级运维e 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"?


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)


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

android:entryValues="@array/listArray"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜