Reading Statics from an Array Named in an Array?
I have a load of hierarchal static configuration data that I want to read, for example;
<string-array name="Root">
<item>Array1</item>
<item>Array2</item>
<item>Array3</item>
</string-array>
<string-array name="Array1">
<item>Array1 Data1</item>
<item>Array1 Data2</item>
<item>Array1 SubArray1</item>
<item>Array1 SubArray2</item>
<item>Array1 SubArray3</item>
</string-array>
<string-array name="Array1 SubArray1">
<item>Array1 SubArray1 Data1</item>
<item>Array1 SubArray1 Data2</item>
</string-array>
<string-array name="Array2">
<item>Array2 Data1</item>
<item>Array2 Data2</item>
<item>Array2 SubArray1</item>
<item>Array2 SubArray2</item>
<item>Array2 SubArray3</item>
</string-array>
<string-array name="A开发者_Go百科rray1 SubArray3">
<item>Array2 SubArray3 Data1</item>
<item>Array2 SubArray3 Data2</item>
</string-array>
Putting in 1,1 would give me;
Array1 Data1, Array1 Data2, Array1 SubArray1 Data1, Array1 SubArray1 Data2While putting in 2,3 would give me;
Array2 Data1, Array2 Data2, Array2 SubArray3 Data1, Array2 SubArray3 Data2What I want to do is something like;
Resources res = getResources();
String[] RootArray = res.getStringArray(R.array.Root);
String[] Array = res.getStringArray(R.array.RootArray[1]);
String[] SubArray = res.getStringArray(R.array.Array[1]);
Is there a way to get this sort of thing to work?
Note: The Array sizes are not necessarily fixed.
Thanks in advance.
MarkThere is no way of implementing this exact behavior using named arrays. However, it's perfectly possible to do so using a custom XML parser, which can be easily written from the XML libraries included with Android.
The problem is that when you reference R
, you are making a reference to an auto-generated, static integer which the android compiler creates to refer to a resource. When you actually compile your application, the java compiler replaces the reference to the number with the actual number. Thus,
res.getStringArray(R.array.MyArray);
really becomes something like
res.getStringArray(0x12345);
which is obviously not an actual "array".
In order to implement your desired functionality, create an XML file in /res/xml/config.xml
:
<my-config>
<array name="Array1">
<data>Item 1</data>
<data>Item 2</data>
<array name="SubArray 1">
<data>Item 4</item>
</array>
</array>
</my-config>
In your application, you can load the XML file by calling
XmlResourceParser XMLparser = getResources().getXml(R.xml.config);
and then use the methods of the XMLResourceParser to pull the appropriate values.
精彩评论