Android Resource - Array of Arrays

Android Resource - Array of Arrays

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!

Add new values to existing resource array

Unfortunately resource values are still immutable. They are generated when your project is compiled and overriden on every compilation. There is a corresponding warning here in the documentation: https://developer.android.com/guide/topics/resources/accessing-resources.html

Nested Arrays in Android xml

This is what I've done to accomplish something like this:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<array name="menu_items">
<item>@array/menu_item_dashboard</item>
<item>@array/menu_item_index</item>
</array>

<array name="menu_item_dashboard">
<item>@drawable/transparent</item>
<item>Dashboard</item>
<item>home</item>
</array>
<array name="menu_item_index">
<item>@drawable/transparent</item>
<item>Title</item>
<item>index</item>
</array>
</resources>

And to access:

TypedArray menuResources = getResources().obtainTypedArray(R.array.menu_items);

TypedArray itemDef;

for (int i = 0; i < menuResources.length(); i++) {
int resId = menuResources.getResourceId(i, -1);
if (resId < 0) {
continue;
}

itemDef = getResources().obtainTypedArray(resId);
//itemDef.getDrawable(0)
//itemDef.getString(1)
//itemDef.getString(2)
}

reference string array res id from an array

Your second array should be an array of string arrays, not string array of string arrays.

I think the way you would do what you need is:

<array name="my_strings_arrays">
<item>@array/str_arr1 </item>
<item>@array/str_arr2 </item>
</array>

Is an array from resource xml file ordered?

Yes. Arrays are ordered.


If they weren't, chaos would ensue.



Related Topics



Leave a reply



Submit