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

时间:2018-02-10 18:28:17

标签: android android-recyclerview adapter android-cardview

我尝试为CardView中的每个RecyclerView项设置图片。

这是我的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());
}

这是我的班级模特:

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;
    }
}

你能告诉我为什么我会收到错误吗?

做正确的方法是什么?

5 个答案:

答案 0 :(得分:1)

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

使用

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

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

注意:getResources()使用context

答案 1 :(得分:0)

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

答案 2 :(得分:0)

你可以使用Glide`

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

答案 3 :(得分:0)

通过Drawable或资源ID,有两种主要方法可以将图像设置为ImageView 您正在使用setImageDrawable,它需要一种Drawable,但您使用getMasarImg()传递一个int。如果您有图像资源ID(它是一个int),那么您可以使用setImageResouce()来设置图像。当然你也可以使用getResources()。getDrawable(这里是一个INT资源)但不推荐使用(如果我没记错的话),所以使用ContextCompat.getDrawable(getActivity(),你的drawable)替换。
大多数时候我会使用ContextCompat方法来获取我的drawable但是记住你需要上下文 - getActivity() - 使用它并且当你在RecyclerView适配器中时你将没有上下文所以你必须传递它在构造函数中。

答案 4 :(得分:0)

@ akhilesh0707的第二个选择是执行以下操作:

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

但是我需要一个Kotlin解决方案,所以我对其进行了修改,这对我来说很有效:

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

希望它可以帮助我,因为我浪费了数小时来尝试解决这个问题。

相关问题