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?
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();
In the value
folder create xml
file name it arrays.xml
add the data to it in this way
<integer-array name="your_array_name">
<item>@drawable/1</item>
<item>@drawable/2</item>
<item>@drawable/3</item>
<item>@drawable/4</item>
</integer-array>
Then obtain it to your code this way
private TypedArray img;
img = getResources().obtainTypedArray(R.array.your_array_name);
Then to use a Drawable
of these in the img
TypedArray
for example as an ImageView
background
use the following code
ImageView.setBackgroundResource(img.getResourceId(index, defaultValue));
where index
is the Drawable
index.
defaultValue
is a value you give if there is no item at this index
For more information about TypedArray
visit this link
http://developer.android.com/reference/android/content/res/TypedArray.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With