Using xml Syntax Highlighting
- <integer-array name="my_array">
- <item>@drawable/my_pic1</item>
- <item>@drawable/my_pic2</item>
- </integer-array>
Parsed in 0.001 seconds, using GeSHi 1.0.8.4
The following WILL NOT WORK:
Using java Syntax Highlighting
- getResources().getIntArray(R.array.my_array);
Parsed in 0.030 seconds, using GeSHi 1.0.8.4
The returned references will be 0.
Here is a workaround for this issue, using the xml shown above:
This concept was adapted from the Android source code at: http://www.netmite.com/android/mydroid/ ... eInit.java
Using java Syntax Highlighting
- TypedArray ar = context.getResources().obtainTypedArray(R.array.my_array);
- int len = ar.length();
- int[] resIds = new int[len];
- for (int i = 0; i < len; i++)
- resIds[i] = ar.getResourceId(i, 0);
- ar.recycle();
- // Do stuff with resolved reference array, resIds[]...
- for (int i = 0; i < len; i++)
- Log.v (TAG, "Res Id " + i + " is " + Integer.toHexString(resIds[i]));
Parsed in 0.032 seconds, using GeSHi 1.0.8.4
TypedArray ar has an .mData member containing among other things, a resolved resource id, which can be retrieved with .getResourceId(), though this is not immediately obvious. I.e., each index of ar is being treated as an attribute, and .getResourceId() gets the resource id for that attribute.
Tested on Android versions 1.1 and 2.0, emulator only.
Additional Notes
- This is a workaround for .getIntArray() failing to resolve resource references (e.g., '@drawable/my_pic1') from integer-array resources. Once .getIntArray() is fixed there will be no need for the above snippet.
- .obtainTypedArray() is retrieving from a compiled resource, so this mechanism should be fast.
- Don't forget to call .recycle().
Interesting aside: Be aware that if you call .recycle() then declare a new TypedArray ar1 = ... you will see the old value (the one that is no longer valid) change in the debugger variable window if it's still present. This threw me for a loop the first time I saw it, until I realized that .recycle() literally recycles that area of memory for use by the next instance of TypedArray, so when you use the new instance you are referencing the same memory location. Obviously the old one is no longer valid, but you may still see it update if it's present in the variable window.
- Hint of the Day: In your Eclipse IDE, turn your variables into hex output so you can easily check your resource ids against R.Java when you debug. In Eclipse (Galileo): Window->Preferences->Java->Debug->Primitive Display Options, check 'Display hexadecimal values'.
Hope this helps!
XCaf



