In an arrays.xml file, in the re开发者_运维技巧s folder, are defined several arrays:
<string-array name="all">
<item> a1 </item>
<item> a2 </item>
</string-array>
<string-array name="a1">
<item> x </item>
<item> y </item>
</string-array>
<string-array name="a2">
<item> z </item>
<item> t </item>
</string-array>
I would like to read the "all" array and sequence into the a1 or a2 arrays dependent on a selection in "all", without having to build a switch/case statement (the real arrays are more complex). The code would look like this, but Java/Android complains about the second line. It wants R.array to be a constant like R.array.a1 or R.array.a2 and not with a variable.
Is it possible to do the following (line 2),
String[] temp_items = getResources().getStringArray(R.array.all1);
String[] items = getResources().getStringArray(R.array.temp_items[0]);
I can also solve this by putting the arrays in a utility class in java and bypassing the arrays.xml file.
Is this possible? a1 a2
<string-array name="a1">
<item> x </item>
<item> y </item>
</string-array>
<string-array name="a2">
<item> z </item>
<item> t </item>
</string-array>
I hope this code to be helpful. You can get the resourceID from the function getIdentifier() by resourceName.
for(int i = 1; i < 3; i++)
{
int arrayID = getResources().getIdentifier("a" + i,"array",getPackageName());
items[i] = getResources().getStringArray(arrayID);
}
The ID that is generated in R.array
isn't the name of the array, it is actually an integer that is generated at compile time. I'm pretty sure this won't be possible without some extra code. You could use reflection to turn the name from all
into the actual int constant in R.array
, but that would be a bit much.
精彩评论