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>

然后,在我的 Java 代码中,我检索数组并尝试像这样访问子元素……

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

TypedValue typedValue = null;

typedArray.getValue(0, typedValue);

此时 typedArray 对象应该表示字符串数组“array01”,但是,我不知道如何检索“id”和“title”字符串元素。任何帮助将不胜感激,在此先感谢。

原文由 JediPotPie 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 402
2 个回答

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

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

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

 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!

原文由 Ted Hopp 发布,翻译遵循 CC BY-SA 3.0 许可协议

https://developer.android.com/guide/topics/resources/more-resources.html#Color

 <?xml version="1.0" encoding="utf-8"?>
<resources>
    <array name="icons">
        <item>@drawable/home</item>
        <item>@drawable/settings</item>
        <item>@drawable/logout</item>
    </array>
    <array name="colors">
        <item>#FFFF0000</item>
        <item>#FF00FF00</item>
        <item>#FF0000FF</item>
    </array>
</resources>

此应用程序代码检索每个数组,然后获取每个数组中的第一个条目:

 Resources res = getResources();
TypedArray icons = res.obtainTypedArray(R.array.icons);
Drawable drawable = icons.getDrawable(0);
TypedArray colors = res.obtainTypedArray(R.array.colors);
int color = colors.getColor(0,0);

原文由 Bill 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题