Storing R.drawable IDs in XML array

You use a typed array in arrays.xml file within your /res/values folder that looks like this:

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <integer-array name="random_imgs">
        <item>@drawable/car_01</item>
        <item>@drawable/balloon_random_02</item>
        <item>@drawable/dog_03</item>
    </integer-array>

</resources>

Then in your activity, access them like so:

TypedArray imgs = getResources().obtainTypedArray(R.array.random_imgs);

// get resource ID by index, use 0 as default to set null resource
imgs.getResourceId(i, 0)

// or set you ImageView's resource to the id
mImgView1.setImageResource(imgs.getResourceId(i, 0));

// recycle the array
imgs.recycle();

Leave a Comment