recyclerview点击事件
时间: 2023-12-25 07:04:40 浏览: 73
在RecyclerView中实现点击事件有两种方式:
1. 在onCreateViewHolder中注册点击事件:
```java
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<String> mData;
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
// ...
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout, parent, false);
final ViewHolder viewHolder = new ViewHolder(view);
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mListener != null) {
int position = viewHolder.getAdapterPosition();
mListener.onItemClick(position);
}
}
});
return viewHolder;
}
// ...
public static class ViewHolder extends RecyclerView.ViewHolder {
// ...
public ViewHolder(View itemView) {
super(itemView);
// ...
}
}
}
```
2. 定义点击动作:
```java
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<String> mData;
public interface OnItemClickListener {
void onItemClick(int position);
}
// ...
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout, parent, false);
final ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
// ...
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 处理点击事件
}
});
}
// ...
public static class ViewHolder extends RecyclerView.ViewHolder {
// ...
public ViewHolder(View itemView) {
super(itemView);
// ...
}
}
}
```
阅读全文