Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
136 views
in Technique[技术] by (71.8m points)

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

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

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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...