在RecyclerView ( OnBindViewHolder方法)中,我无法获得位于ViewHolder类中的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);
}
}
}发布于 2020-09-12 19:20:29
我认为有一件事可能是,您将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;
}
}此模型将包含要显示的信息。现在在您的ArrayList类中创建一个RecyclerView:
//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中的项为每个单元格设置属性。
https://stackoverflow.com/questions/63863767
复制相似问题