Reference drawable from string-array in android
Solution 1
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();
Solution 2
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.
learner
Updated on July 28, 2022Comments
-
learner almost 2 years
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?
-
Display Name over 9 yearsGreat answer, but it was hard to find. There are so many similar answers and questions.
-
Lorne Laliberte over 8 yearsI'd recommend using 0 as the default instead of -1. 0 will never be returned as it is reserved to designate a missing (null) resource, whereas -1 is a valid id value. Although the build will not automatically assign -1, it is still considered a valid id, and it is common to use such values when assigning ids programmatically (for example, in wrapping adapters), in order to avoid collisions with the range of integers that could be assigned automatically during the build.
-
KlevisGjN over 7 yearsPerfect, this is what i was looking for.