将图像资源设置为 RecyclerView 列表项

Setting image resource to RecyclerView list items

我正在尝试为 RecyclerView 中的每个 CardView 项目设置图像。

这是我的 onBindViewHolder :

@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
    Masar masar=masrList.get(position);
    holder.masarName.setText(masar.getMasarTitle());
    holder.masarDesc.setText(masar.getMasarDescreption());

    // why i'm getting error here
    holder.masarImg.setImageDrawable(masar.getMasarImg());
}

这是我的 class 模型:

public class Masar {
    public String masarTitle;
    public String masarDescreption;
    public int masarImg;

    public Masar(String masarTitle, String masarDescreption) {
        this.masarTitle = masarTitle;
        this.masarDescreption = masarDescreption;
    }

    public Masar(String masarTitle, String masarDescreption, int masarImg) {
        this.masarTitle = masarTitle;
        this.masarDescreption = masarDescreption;
        this.masarImg = masarImg;
    }

    public String getMasarTitle() {
        return masarTitle;
    }

    public String getMasarDescreption() {
        return masarDescreption;
    }

    public int getMasarImg() {
        return masarImg;
    }

    public void setMasarImg(int masarImg) {
        this.masarImg = masarImg;
    }
}

你能告诉我为什么会出错吗?

正确的方法是什么?

改用holder.masarImg.setImageResource(masar.getMasarImg());

而不是使用 holder.masarImg.setImageDrawable(masar.getMasarImg());

使用

holder.masarImg.setImageDrawable(getResources().getDrawable(masar.getMasarImg()));

holder.masarImg.setImageResource(masar.getMasarImg());

注意: 得到 getResources() 使用 context

你可以使用 Glide `

             Glide.with(context)
            .load(where image live)
            .into(holder.your imageview);`

有两种主要方法可以通过 Drawable 或 Resource Id 将图像设置为 ImageView。
您正在使用 setImageDrawable,它需要一种 Drawable,但您正在使用 getMasarImg() 传递一个 int。如果您有图像资源 ID(这是一个 int),那么您可以使用 setImageResouce() 来设置图像。当然,您也可以改用 getResources().getDrawable(此处为 INT 资源),但这已被弃用(如果我没记错的话),因此请使用 ContextCompat.getDrawable(getActivity(),此处为您的可绘制对象)作为替代。
大多数时候,我会使用 ContextCompat 方式来获取我的可绘制对象,但请记住,您需要上下文 - getActivity() - 才能使用它,因为您在 RecyclerView 适配器中,您将没有上下文,因此您必须传递它在构造函数中。

@akhilesh0707 的第二个选择是:

holder.masarImg.setImageResource(masar.getMasarImg());

但我需要一个 Kotlin 解决方案,所以我修改了它,这对我有用:

holder.masarImg.setImageResource(R.drawable.myfile.png)

希望它能帮助别人,因为我浪费了几个小时试图解决这个问题。