EDIT 我(将onClick移动到onBindViewHolder但仍未成功
我尝试使用RecyclerView创建应用程序,您可以在其中查看项目的详细信息。所以你有一个带照片及其标题的项目列表。当您单击它时,将显示新屏幕,其中包含新/不同的照片,相同的标题和其他文本。 应用程序设计与图片
相同我的适配器的代码是:
公共类RecyclerAdapter扩展了recyclerView.Adapter {
private String[] titles = {
"Title A",
"Title B",
"Title C"};
private String[] description = {
"Description A",
"Description B",
"Description C"};
private int[] images = {
R.drawable.picture A,
R.drawable.picture B,
R.drawable.picture C,};
private int[] images2 = {
R.drawable.picture A2,
R.drawable.picture B2,
R.drawable.picture C2,
};
class ViewHolder extends RecyclerView.ViewHolder{
public ImageView itemImage;
public ImageView itemImage2;
public TextView itemTitle;
public TextView itemTitle2;
public ViewHolder(View itemView) {
super(itemView);
itemImage = (ImageView)itemView.findViewById(R.id.image_start);
itemTitle = (TextView)itemView.findViewById(R.id.article_title);
//SecondActivity where different picture and decription should be displayed, but when I uncomment it the app crashes
//itemTitle2 =(TextView)itemView.findViewById(R.id.article_ingredients);
//itemImage = (ImageView)itemView.findViewById(R.id.image_details);
itemView.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
int position = getAdapterPosition();
Intent intent = new Intent(v.getContext(), SecondActivity.class);
intent.putExtra("title",itemTitle.getText().toString());
intent.putExtra("description", itemTitle2.getText().toString()); //this one on makes app crash
v.getContext().startActivity(intent);
}
});
}
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.article_layout, viewGroup, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
@Override
public void onBindViewHolder(ViewHolder viewHolder, int i) {
viewHolder.itemTitle.setText(titles[i]);
// viewHolder.itemDetail.setText(details[i]);
viewHolder.itemImage.setImageResource(images[i]);
// viewHolder.itemTitle2.setText(titles2[i]);
}
@Override
public int getItemCount() {
return titles.length;
}
}
我尝试了不同的选择,但没有结果。在此先感谢您的帮助
答案 0 :(得分:0)
您已注释掉itemTitle2 =(TextView)itemView.findViewById(R.id.article_ingredients);
,当您尝试在其上调用getText()
时,可能会导致空指针异常。
取消注释该行,然后在onBindViewHolder中取消注释此行:viewHolder.itemTitle2.setText(titles2[i]);
。
如果您收到新错误,请告诉我并确保为我们添加堆栈跟踪。