69

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)?

Andrew T.
  • 4,701
  • 8
  • 43
  • 62
android_stricken
  • 703
  • 1
  • 5
  • 5

4 Answers4

70

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

resnbl
  • 1,443
  • 13
  • 10
  • This seems to work for drawables but not for styles for example: @android:style/Theme @android:style/Theme.Light @android:style/Theme.Holo @android:style/Theme.Holo.Light How can this work for other resource ids aside from drawables? – Etienne Lawlor Sep 13 '12 at 04:33
  • I think, as far as i know, is create an int array representing the pre-compiled value itself and not the value what it represents. if someone has any idea it's welcome. – AXSM Oct 31 '14 at 22:32
53

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]));
Joe Bowbeer
  • 3,574
  • 3
  • 36
  • 47
2

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

xandy
  • 27,357
  • 8
  • 59
  • 64
0

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...};
android developer
  • 114,585
  • 152
  • 739
  • 1,270