[英]Cannot assign value to specific textView in RecyclerView.Adapter
I'm new to android dev and I wanted to make app with fragments and use RecyclerView inside it. 我是android开发人员的新手,我想使用片段制作应用程序并在其中使用RecyclerView。 I'm getting error which is saying that I'm trying to use setText on a null object. 我收到错误消息,这表示我正在尝试在null对象上使用setText。 My code looks like that : 我的代码如下所示:
public static class ContentAdapter extends RecyclerView.Adapter<ContentAdapter.ViewHolder> {
private static String[] newsTitle = new String[] {...};
private static String[] newsDescs = new String[] {...};
public ContentAdapter(ViewGroup parent) {}
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
public static class ViewHolder extends RecyclerView.ViewHolder {
TextView titles;
TextView descs;
public ViewHolder(LayoutInflater inflater, ViewGroup parent) {
super(inflater.inflate(R.layout.item_list, parent, false));
titles = (TextView) parent.findViewById(R.id.list_title);
descs = (TextView) parent.findViewById(R.id.list_desc);
}
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(parent.getContext()), parent);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.titles.setText(newsTitle[position]); //Here is error
holder.descs.setText(newsDescs[position]);
}
@Override
public int getItemCount() { return newsTitle.length; }
}
Here is a correct example if a view holder 这是一个正确的例子,如果一个视图持有人
public static class HeaderVH extends RecyclerView.ViewHolder {
public TextView textView;
public HeaderVH(View view){
super(view);
textView = (TextView)view;
}
}
You need to pass in a the View object of the row to the viewholder, not the parent View object. 您需要将行的View对象传递给Viewholder,而不是父View对象。 This is an example of onCreateViewHolder() 这是onCreateViewHolder()的示例
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_setting_header, parent, false);
RecyclerView.ViewHolder vh = new HeaderVH(v);
return vh;
}
https://developer.android.com/reference/android/support/v7/widget/RecyclerView.ViewHolder.html https://developer.android.com/reference/android/support/v7/widget/RecyclerView.ViewHolder.html
https://www.bignerdranch.com/blog/recyclerview-part-1-fundamentals-for-listview-experts/ https://www.bignerdranch.com/blog/recyclerview-part-1-fundamentals-for-listview-experts/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.