157

我想R.drawable.*使用 XML 值文件以数组内部的形式存储可绘制资源的 ID,然后在我的活动中检索该数组。

关于如何实现这一目标的任何想法?

4

5 回答 5

377

您在文件夹中的文件中使用类型化数组,如下所示:arrays.xml/res/values

<?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>

然后在您的活动中,像这样访问它们:

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();
于 2011-08-04T17:24:22.697 回答
32

value文件夹中创建xml文件名arrays.xml ,它以这种方式将数据添加到其中

<integer-array name="your_array_name">
    <item>@drawable/1</item>
    <item>@drawable/2</item>
    <item>@drawable/3</item>
    <item>@drawable/4</item>
</integer-array>

然后以这种方式将其获取到您的代码中

private TypedArray img;
img = getResources().obtainTypedArray(R.array.your_array_name);

然后Drawableimg TypedArray示例中使用其中的一个作为ImageView background使用以下代码

ImageView.setBackgroundResource(img.getResourceId(index, defaultValue));

索引 index在哪里。是您在此处没有项目时给出的值DrawabledefaultValueindex

有关TypedArray访问此链接 的更多信息http://developer.android.com/reference/android/content/res/TypedArray.html

于 2015-09-28T18:12:09.640 回答
16

您可以使用它来创建一系列其他资源,例如可绘制对象。请注意,数组不需要是同质的,因此您可以创建混合资源类型的数组,但您必须知道数据类型在数组中的内容和位置。

 <?xml version="1.0" encoding="utf-8"?>
<resources>
    <array name="icons">
        <item>@drawable/home</item>
        <item>@drawable/settings</item>
        <item>@drawable/logout</item>
    </array>
    <array name="colors">
        <item>#FFFF0000</item>
        <item>#FF00FF00</item>
        <item>#FF0000FF</item>
    </array>
</resources>

并像这样获取您活动中的资源

Resources res = getResources();
TypedArray icons = res.obtainTypedArray(R.array.icons);
Drawable drawable = icons.getDrawable(0);

TypedArray colors = res.obtainTypedArray(R.array.colors);
int color = colors.getColor(0,0);

享受!!!!!

于 2015-07-07T16:24:03.520 回答
3

在 Kotlin 中,您可以执行以下操作:-

 <integer-array name="drawer_icons">
    <item>@drawable/drawer_home</item>
</integer-array>

您将从资源中获取图像数组TypedArray

 val imageArray = resources.obtainTypedArray(R.array.drawer_icons)

通过索引获取资源ID

imageArray.getResourceId(imageArray.getIndex(0),-1)

或者您可以将 imageView 的资源设置为 id

imageView.setImageResource(imageArray.getResourceId(imageArray.getIndex(0),-1))

并在最后回收阵列

imageArray.recycle()
于 2019-10-30T15:30:31.150 回答
1

kotlin 的方式可能是这样的:

fun Int.resDrawableArray(context: Context, index: Int, block: (drawableResId: Int) -> Unit) {
  val array = context.resources.obtainTypedArray(this)
  block(array.getResourceId(index, -1))
  array.recycle()
}

R.array.random_imgs.resDrawableArray(context, 0) {
  mImgView1.setImageResource(it)
}
于 2019-06-21T14:57:19.033 回答