java 如何在Android中按名称从类型化数组资源中获取值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12675428/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get a value from a typed array resource by name in Android?
提问by Adam Arold
Suppose I have a resource xml file like this:
假设我有一个像这样的资源 xml 文件:
<?xml version="1.0" encoding="UTF-8"?>
<resources>
<array name="difficulties">
<item>
<integer name="level">1</integer>
<integer name="fixed_blocks">2</integer>
<integer name="color_count">2</integer>
</item>
<item>
<integer name="level">2</integer>
<integer name="fixed_blocks">4</integer>
<integer name="color_count">3</integer>
</item>
<item>
<integer name="level">3</integer>
<integer name="fixed_blocks">6</integer>
<integer name="color_count">3</integer>
</item>
</array>
</resources>
How can I get the integer values from an item
by name? The TypedValue
's API doesn't seem to contain any methods for this. If this is not possible with the TypedArray
how IS it?
如何从item
名称中获取整数值?本TypedValue
的API似乎并没有包含这方面的任何方法。如果这是不可能的TypedArray
怎么办?
If I can get a value from an item by its ordinal it will be OK too.
如果我可以通过它的序数从一个项目中获得一个值,它也可以。
回答by Luksprog
I don't recall this being possible(but I could be wrong). Judging by the structure of an item(in the difficulties
array) you could do something else, you could use an array of integer arrays. Knowing that the item array has level
at the first position, fixed_blocks
as the second position etc you could easily get the values. An example of this you can find here Android Resource - Array of Arrays
我不记得这是可能的(但我可能是错的)。根据项目(在difficulties
数组中)的结构判断,您可以做其他事情,您可以使用整数数组的数组。知道 item 数组level
位于第一个位置,fixed_blocks
作为第二个位置等,您可以轻松获取值。你可以在这里找到一个例子Android Resource - Array of Arrays
Edit:Is this the method you're looking for?
编辑:这是您正在寻找的方法吗?
private int[] getLevelConstants(int level) {
int[] result = null;
TypedArray ta = getResources().obtainTypedArray(R.array.difficulties);
// keep in mind the differences between the level(starts at 1) and the index of the difficulties array which starts at 0
int id = ta.getResourceId(level, 0);
if (id > 0) {
result = getResources().getIntArray(id);
} else {
// something bad
}
return result;
}
and the array will be:
数组将是:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<integer-array name="difficulties">
<item>@array/level1</item>
<item>@array/level2</item>
</integer-array>
<integer-array name="level1" >
<item>1</item>
<item>2</item>
<item>2</item>
</integer-array>
<integer-array name="level2" >
<item>2</item>
<item>4</item>
<item>3</item>
</integer-array>
</resources>