CardLayout 和回收视图无法在 viewholder 中获取我的视图元素

CardLayout and recycle view can't get my view elements in viewholder

我正在尝试使用适配器构建一个简单的回收视图,我正在按照 this 教程来实现它。

当我在我的适配器上设置内部的所有内容时,我收到一条错误消息,提示我需要将我的所有元素(TextViews 和那些)转换为静态字段,作者不需要那个,我也不知道为什么。

这是我的代码:

public class SimiliarPlantsAdapter extends RecyclerView.Adapter<SimiliarPlantsAdapter.PlantViewHolder>{

ArrayList<Plant> plants = new ArrayList<Plant>();

public static class PlantViewHolder extends RecyclerView.ViewHolder {
    CardView cv;
    TextView plantName;
    TextView plantCheck;
    ImageView plantPhoto;

    PlantViewHolder(View itemView) {
        super(itemView);
        cv = (CardView)itemView.findViewById(R.id.cv);
        plantName = (TextView)itemView.findViewById(R.id.plantName);
        plantCheck = (TextView)itemView.findViewById(R.id.plantCheck);
        plantPhoto = (ImageView)itemView.findViewById(R.id.plantPhoto);
    }

}

@Override
public PlantViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
    View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.similiar_photo_row, viewGroup, false);
    PlantViewHolder pvh = new PlantViewHolder(v);
    return pvh;
}

@Override
public void onBindViewHolder(PlantViewHolder holder, int position) {
    PlantViewHolder.plantName.setText(plants.get(position).getSpecie());
    PlantViewHolder.plantCheck.setText("Are you sure this is the plant?");
    PlantViewHolder.personPhoto.setImageResource(plants.get(position).photoId);
}


@Override
public int getItemCount() {
    return plants.size();
}

public SimiliarPlantsAdapter(ArrayList<Plant> plants) {
    this.plants = plants;
}

问题在这里:

@Override
    public void onBindViewHolder(PlantViewHolder holder, int position) {
        PlantViewHolder.plantName.setText(plants.get(position).getSpecie());
        PlantViewHolder.plantCheck.setText("Are you sure this is the plant?");
        PlantViewHolder.personPhoto.setImageResource(plants.get(position).photoId);
    }

我的 plantName 和 plantCheck 不起作用,我需要将初始化值转换为静态字段,为什么会这样,有提示吗?

谢谢

更改 onBindViewHolder 方法 我认为您访问属性的方式 PlantViewHolder class 是 wrong.do 像这样

@Override
public void onBindViewHolder(PlantViewHolder holder, int position) {
    holder.plantName.setText(plants.get(position).getSpecie());
    holder.plantCheck.setText("Are you sure this is the plant?");
}

您不必使用 static holder 对象 已在方法内部传递 尝试使用传递的引用访问它的变量 e

使用PlantViewHolder's对象holder设置views属性.

更新 onBindViewHolder 如下:

@Override
public void onBindViewHolder(PlantViewHolder holder, int position) {
    holder.plantName.setText(plants.get(position).getSpecie());
    holder.plantCheck.setText("Are you sure this is the plant?");
    holder.personPhoto.setImageResource(plants.get(position).photoId);
}