Reference drawable from string-array in android [d

2019-03-14 03:31发布

This question already has an answer here:

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?

2条回答
可以哭但决不认输i
2楼-- · 2019-03-14 03:59

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.

查看更多
3楼-- · 2019-03-14 04:13

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();
查看更多
登录 后发表回答