与键值的Android名单 [英] Android List of values with key
问题描述
我试图找出如果我可以用一个资源文件,同时开发我的Android应用程序,持有使用字符串值作为密钥号码清单。例如:
I am trying to work out if I can use a resource file, while developing my android app, to hold a list of numbers using a string value as a key. For example
数字(UK)= 999
数字(US)= 911
numbers("UK")= 999 numbers("US") = 911
正如我所说的,这将理想的资源文件,而不是一个Java类,因为它是更易于维护。
As I said, this would ideally be in resource file rather than a Java class as it is more maintainable
推荐答案
您要定义的资源字典。有没有办法直接做到这一点。但是,您可以定义键和值阵列,然后生成字典。
You want to define a dictionary in resources. There's no way to do that directly. You could however define the keys and values as arrays, then build the dictionary.
在 RES /价值/ arrays.xml
,有这样的事,
<string-array name="emergency_keys">
<item>UK</item>
<item>US</item>
....
</string-array>
<integer-array name="emergency_values">
<item>999</item>
<item>911</item>
...
</integer-array>
然后在你的code你有这样的实用方法,
Then in your code you have this utility method,
Map<String,Integer> getDict(int keyId, int valId) {
String[] keys = getResources().getStringArray(keyId);
int[] values = getResources().getIntArray(valid);
Map<String,Integer> dict = new HashMap<String,Integer>();
for (int i = 0, l = keys.length; i < l; i++) {
dict.put(keys[i], vals[i]);
}
return dict;
}
在您需要的字典在code,为此,
When you need the dictionary in your code, do this,
Map<String,Integer> emergencyNumbers = getDict(R.array.emergency_keys, R.array.emergency_values);
这篇关于与键值的Android名单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!