Android 资源 - 数组数组 [英] Android Resource - Array of Arrays

查看:37
本文介绍了Android 资源 - 数组数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 代码中,我检索数组并尝试像这样访问子元素...

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 对象应该表示字符串数组array01",但是,我不知道如何检索id"和title"字符串元素.任何帮助将不胜感激,提前致谢.

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>

然后在您的代码中执行以下操作:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆