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

时间:2018-05-09 15:59:50

标签: android int drawable 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

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

2 个答案:

答案 0 :(得分:1)

尝试:

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

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

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();

希望它有所帮助。

答案 1 :(得分:0)

感谢您的回答,但我没有尝试过。也许它有效,但我发现了一个更好的,可能是有意的解决方案。而不是使用setImageResource()我使用setImageDrawable()