在RecyclerView中,在OnBindViewHolder方法中

问题描述

RecyclerView的{​​{1}}方法中,我无法获得OnBindViewHolder类中的TextViews。 为什么?有什么问题吗?

请参阅屏幕截图:

enter image description here

下面是我的代码

ViewHolder

解决方法

我认为可能是您将ViewHolder保留在RecyclerViewAdapter类之外。将ViewHolder保留在其中,或尝试将两个TextViews保持公开。


输入所有这些内容后,我意识到它不能回答您的问题,因此我将其保留在下面,以备日后参考。

因此,它无法像您那样使用。您需要有一个包含对象的ArrayList,每个对象都将包含放置位置的信息。我将添加代码以更好地解释:

在您的示例中,每个单元格仅包含一个TextView,因此请创建一个模型类,并根据需要命名它。

public class Model{

   //Variable that will store the text
   private String text;

   //Constructor for the text
   public Model(String text){ 
      this.text = text;
   }

   //Add setters and getters for the text variable as well.
   public String getText(){return text}

   public void setText(String text){
       this.text = text;
   }
}

此模型将包含要显示的信息。现在,在您的RecyclerView类中创建一个ArrayList:

//You can initialize in Constructor as well.
private ArrayList<Model> cellsList = new ArrayList<>(); 

//Set the ArrayList
public void setList(ArrayList<Model> list){

   cellsList = list;
   notifyDataSetChanged();
}

最后,在onBindViewHolder方法中,使用ArrayList中的项目设置每个单元的属性。