在RecyclerView的Adapter中,需要手动设置item的click监听器,而不能直接使用setOnClickListener()方法。具体步骤如下:
1、在ViewHolder中设置监听器:
public class MyViewHolder extends RecyclerView.ViewHolder { public TextView textView;
public MyViewHolder(View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.text_view);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int position = getAdapterPosition();
//处理点击事件
}
});
}
}
2、在Adapter中重写onBindViewHolder()方法并为ViewHolder设置数据:
public class MyAdapter extends RecyclerView.Adapter
public MyAdapter(List data) {
this.data = data;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout, parent, false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
((MyViewHolder) holder).textView.setText(data.get(position));
}
@Override
public int getItemCount() {
return data.size();
}
}
通过以上步骤,RecyclerView中的item点击事件就可以正常响应了。