Storing R.drawable IDs in XML array

gammaraptor picture gammaraptor · Aug 4, 2011 · Viewed 88.8k times · Source

I would like to store drawable resources' ID in the form of R.drawable.* inside an array using an XML values file, and then retrieve the array in my activity.

Any ideas of how to achieve this?

Answer

Patrick Kafka picture Patrick Kafka · Aug 4, 2011

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