从 xml 到 int 的可绘制数组用于回收器适配器

Drawable array from xml into int for recycler adapter

这是我放入的众多数组之一。xml

<array name="clrs">
        <item>@drawable/red_bg</item>
        <item>@drawable/yellow_bg</item>
        <item>@drawable/green_bg</item>
        <item>@drawable/white_bg</item>
        <item>@drawable/white_bg</item>
        <item>@drawable/white_bg</item>
    </array>

当我使用 getResources().getIntArray(R.array.clrs); 结果是 0 int
在官方 android 开发者上它说这样使用它:

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

但是类型是 drawable,我需要一个 int 用于我的回收器适配器

setImageResource(myCustomItem.getImage());//must be int

如何更改类型或使用不同的方法在卡片视图上显示图像?

尝试:

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

  <integer-array name="random_imgs">
    <item>@drawable/red_bg</item>
    <item>@drawable/yellow_bg</item>
    <item>@drawable/green_bg</item>
    <item>@drawable/white_bg</item>
    <item>@drawable/white_bg</item>
    <item>@drawable/white_bg</item>
  </integer-array>

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

TypedArray imgs = getResources().obtainTypedArray(R.array.random_imgs);

// get resource ID by index
imgs.getResourceId(i, -1)

// or set you ImageView's resource to the id
mImgView1.setImageResource(imgs.getResourceId(i, -1));

// recycle the array
imgs.recycle();

希望对您有所帮助。

感谢您的回答,但我没有试过。也许它有效,但我找到了一个更好的、可能是预期的解决方案。我没有使用 setImageResource(),而是使用 setImageDrawable()