Home » Android » Reference drawable from string-array in android

Reference drawable from string-array in android

Posted by: admin June 15, 2020 Leave a comment

Questions:

how would I reference a drawable resource from the string xml file?
I want to do

<string-array name="my_array">
<item>@drawable/my_image</item>
...

How would I do that?

How to&Answers:

for arrays of drawables ids, don’t use string array just use <array>

then to use them, get a TypedArray if the ids

TypedArray images = getResources().obtainTypedArray(R.array.my_image_ids);
int resourceId = images.getResourceId(id, -1);

and don’t forget when you’re done with the resource id and array to recycle it

images.recycle();

Answer:

I guess you are trying to store all of your image resource names (as string) inside an array and be called when you write your java code?

Resources res = getResources();
String[] images = res.getStringArray(R.array.my_array);

Would get your string array into an array. You can get the item you want by accessing the array as usual.

String image_name = images[0];

http://developer.android.com/guide/topics/resources/string-resource.html

If you are trying to achieve to load a list of images to a gridview, you might want to refer to this:

http://developer.android.com/guide/topics/ui/layout/gridview.html

They have placed the array in the base adapter, like this:

private Integer[] mThumbIds = {
        R.drawable.sample_2, R.drawable.sample_3,
        R.drawable.sample_4, R.drawable.sample_5,
        R.drawable.sample_6, R.drawable.sample_7,
        R.drawable.sample_0, R.drawable.sample_1,
        R.drawable.sample_2, R.drawable.sample_3,
        R.drawable.sample_4, R.drawable.sample_5,
        R.drawable.sample_6, R.drawable.sample_7,
        R.drawable.sample_0, R.drawable.sample_1,
        R.drawable.sample_2, R.drawable.sample_3,
        R.drawable.sample_4, R.drawable.sample_5,
        R.drawable.sample_6, R.drawable.sample_7
};

Which you can easy use just like how you would access an array.