Creating integer array of resource IDs

AndroidArraysAndroid Resources

Android Problem Overview


I have some images in my res/drawable folder. Let's say img1.png, img2.png and img3.png. I am currently creating an integer array of these image IDs in Java like this

int[] imgIds = {R.drawable.img1, R.drawable.img2, R.drawable.img3};

Instead, is it possible to create an integer array in one of res/values files (say strings.xml) like this

<integer-array name="img_id_arr">
    <item>@drawable/img1</item>
    <item>@drawable/img2</item>
    <item>@drawable/img3</item>
</integer-array>

and then access it in Java via getResources().getIntArray(R.array.img_id_arr)?

Android Solutions


Solution 1 - Android

Use just "array" instead of "integer-array". See Typed Array in the developer guide.

Solution 2 - Android

See XML integer array, resource references, getIntArray

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

Solution 3 - Android

Make a LevelListDrawable. Although it is not exactly what you want, but pretty much achievable.

Solution 4 - Android

I think it's best to keep them in code.

private static final int[] AVATARS = new int[]{
            R.drawable.ava_1, R.drawable.ava_2, R.drawable.ava_3...};

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionandroid_strickenView Question on Stackoverflow
Solution 1 - AndroidresnblView Answer on Stackoverflow
Solution 2 - AndroidJoe BowbeerView Answer on Stackoverflow
Solution 3 - AndroidxandyView Answer on Stackoverflow
Solution 4 - Androidandroid developerView Answer on Stackoverflow