[英]Android listpreference - fetching value
I have a listpreference
. 我有一个
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部分的
preferences.xml
中有这个代码:
<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".
因此,如果我选择梅赛德斯,我得到的值是“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)
在你的吐司中,用
cars.get(listpref)
检索汽车名称
您只需要在条目中的entryValues中放入相同的数组
android:entryValues="@array/listArray"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.