Android的资源 - 数组的数组 [英] Android Resource - Array of Arrays
问题描述
我想实现资源数据结构包括一个数组的数组,特别是字符串。我遇到的问题是如何让子阵列对象及其具体数值。这里是我的资源文件看起来像......
I am trying to implement a resource data structure that includes an array of arrays, specifically strings. The issue I run into is how to get the sub-array objects and their specific values. Here is what my resource file looks like....
<resources>
<array name="array0">
<item>
<string-array name="array01">
<item name="id">1</item>
<item name="title">item one</item>
</string-array>
</item>
<item>
<string-array name="array02">
<item name="id">2</item>
<item name="title">item two</item>
</string-array>
</item>
<item>
<string-array name="array03">
<item name="id">3</item>
<item name="title">item three</item>
</string-array>
</item>
</array>
</resources>
于是,在我的Java code我找回阵列和尝试访问的子元素,像这样......
Then, in my Java code I retrieve the array and try to access the sub elements like so...
TypedArray typedArray = getResources().obtainTypedArray(R.array.array0);
TypedValue typedValue = null;
typedArray.getValue(0, typedValue);
在这一点上typedArray对象应重新present字符串数组array01,但我看不出如何检索ID和称号字符串元素。任何帮助将是AP preciated,在此先感谢。
At this point the typedArray object should represent the string-array "array01", however, I don't see how to retrieve the "id" and "title" string elements. Any help would be appreciated, thanks in advance.
推荐答案
您几乎可以做你想做的。你必须单独申报每个数组,然后引用数组。事情是这样的:
You can almost do what you want. You have to declare each array separately and then an array of references. Something like this:
<string-array name="array01">
<item name="id">1</item>
<item name="title">item one</item>
</string-array>
<!-- etc. -->
<array name="array0">
<item>@array/array01</item>
<!-- etc. -->
</array>
然后在你的code,你做这样的事情:
Then in your code you do something like this:
Resources res = getResources();
TypedArray ta = res.obtainTypedArray(R.array.array0);
int n = ta.length();
String[][] array = new String[n][];
for (int i = 0; i < n; ++i) {
int id = ta.getResourceId(i, 0);
if (id > 0) {
array[i] = res.getStringArray(id);
} else {
// something wrong with the XML
}
}
ta.recycle(); // Important!
这篇关于Android的资源 - 数组的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!