Android的存储R.drawable。在XML数组ids数组、drawable、Android、ids

2023-09-11 20:16:36 作者:如初丶

我想存储的图像标识在R.drawable的形式。*使用XML文件值的数组里面,然后检索我的活动阵列。任何想法如何实现这一目标?谢谢你。

I would like to store image Id's 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? Thanks.

推荐答案

您使用在在您的资源文件夹arrays.xml文件类型数组看起来是这样的:

You use a typed array in arrays.xml file within your res folder that looks like this:

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string-array name="random_imgs">
        <item>@drawable/car_01</item>
        <item>@drawable/balloon_random_02</item>
        <item>@drawable/dog_03</item>
    </string-array>

</resources>

然后在你的活动访问它们像这样:

Then in your activity access them like so:

TypedArray imgs = getResources().obtainTypedArray(R.array.random_imgs);
//get resourceid by index
imgs.getResourceId(i, -1)
// or set you ImageView's resource to the id
mImgView1.setImageResource(imgs.getResourceId(i, -1));

编辑:

由benoffi7建议建议:

Suggested recommendation by benoffi7:

使用IMGS之后添加以下行: imgs.recycle();

After using "imgs" add the following line: imgs.recycle();