recycler view的item view怎么设置单击事件
时间: 2023-09-12 13:03:49 浏览: 139
RecyclerViewitem的点击事件
可以在RecyclerView的适配器中给item view设置单击事件监听器。具体可以参考下面的代码:
```
public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {
private List<String> mDataList;
private OnItemClickListener mListener;
public MyAdapter(List<String> dataList, OnItemClickListener listener) {
mDataList = dataList;
mListener = listener;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_view, parent, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
String data = mDataList.get(position);
holder.bindData(data);
}
@Override
public int getItemCount() {
return mDataList.size();
}
public interface OnItemClickListener {
void onItemClick(int position);
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView mTextView;
public MyViewHolder(View itemView) {
super(itemView);
mTextView = itemView.findViewById(R.id.text_view);
itemView.setOnClickListener(this);
}
public void bindData(String data) {
mTextView.setText(data);
}
@Override
public void onClick(View v) {
if (mListener != null) {
int position = getAdapterPosition();
mListener.onItemClick(position);
}
}
}
}
```
在Activity或Fragment中设置单击事件监听器:
```
MyAdapter adapter = new MyAdapter(dataList, new MyAdapter.OnItemClickListener() {
@Override
public void onItemClick(int position) {
// 处理单击事件
}
});
recyclerView.setAdapter(adapter);
```
阅读全文