Android资源 - 数组数组

Jed*_*Pie 43 java xml android

我正在尝试实现一个包含数组数组的资源数据结构,特别是字符串.我遇到的问题是如何获取子数组对象及其特定值.这是我的资源文件的样子....

<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>
Run Code Online (Sandbox Code Playgroud)

然后,在我的Java代码中,我检索数组并尝试访问子元素,如此...

TypedArray typedArray = getResources().obtainTypedArray(R.array.array0);

TypedValue typedValue = null;

typedArray.getValue(0, typedValue);
Run Code Online (Sandbox Code Playgroud)

此时,typedArray对象应该表示字符串数组"array01",但是,我没有看到如何检索"id"和"title"字符串元素.任何帮助将不胜感激,提前谢谢.

Ted*_*opp 115

你几乎可以做你想做的事.您必须分别声明每个数组,然后是一个引用数组.像这样的东西:

<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>
Run Code Online (Sandbox Code Playgroud)

然后在你的代码中你做这样的事情:

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!
Run Code Online (Sandbox Code Playgroud)