在 RecyclerView 中,在 OnBindViewHolder 方法中

in RecyclerView, in OnBindViewHolder method

RecyclerView中,OnBindViewHolder方法,我无法获取位于ViewHolderclass中的TextViews。 为什么?有什么问题?

请参考截图:

我的代码如下:

public class MainActivity extends AppCompatActivity  {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ((CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar_layout)).setTitle("Screen Title");

        RecyclerView rv = findViewById(R.id.recyclerview);
        rv.setLayoutManager(new LinearLayoutManager(this));
        rv.setAdapter(new RecyclerView.Adapter<RecyclerView.ViewHolder>() {
            @Override
            public RecyclerView.ViewHolder  onCreateViewHolder(ViewGroup parent, int position) {
                View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
                return new ViewHolder(view);}

            @Override
            public void onBindViewHolder(RecyclerView.ViewHolder  viewHolder, int position) {
                viewHolder.text1.setText("Bacon");
                viewHolder.text2.setText("Bacon ipsum dolor amet pork belly meatball kevin spare ribs. Frankfurter swine corned beef meatloaf, strip steak.");
            }

            @Override
            public int getItemCount() {
                return 30;
            }
        });
    }// on create method END

    private static class ViewHolder extends RecyclerView.ViewHolder {
        TextView text1;
        TextView text2;

        public ViewHolder(View itemView) {
            super(itemView);
            text1 = itemView.findViewById(android.R.id.text1);
            text2 = itemView.findViewById(android.R.id.text2);
        }
    }
}

我认为一件事可能是您将 ViewHolder 保留在 RecyclerViewAdapter 之外 class。将 ViewHolder 保留在其中或尝试同时保留 TextViews public.


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

所以它不会按照您的方式工作。您需要有一个包含对象的 ArrayList,每个对象都包含有关放置内容的信息。我将添加代码以更好地解释:

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

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 class:

//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 中的项目设置每个单元格的属性。