recyclerview点击事件的代码
时间: 2023-06-20 19:10:39 浏览: 95
RecyclerView 的点击事件可以通过设置 `OnItemClickListener` 或者 `OnItemLongClickListener` 来实现。
以下是一个简单的示例:
```java
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private List<String> mData;
private OnItemClickListener mOnItemClickListener;
private OnItemLongClickListener mOnItemLongClickListener;
public MyAdapter(List<String> data) {
mData = data;
}
public void setOnItemClickListener(OnItemClickListener listener) {
mOnItemClickListener = listener;
}
public void setOnItemLongClickListener(OnItemLongClickListener listener) {
mOnItemLongClickListener = listener;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout, parent, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
holder.textView.setText(mData.get(position));
}
@Override
public int getItemCount() {
return mData.size();
}
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {
private TextView textView;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.text_view);
itemView.setOnClickListener(this);
itemView.setOnLongClickListener(this);
}
@Override
public void onClick(View v) {
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(getAdapterPosition());
}
}
@Override
public boolean onLongClick(View v) {
if (mOnItemLongClickListener != null) {
return mOnItemLongClickListener.onItemLongClick(getAdapterPosition());
}
return false;
}
}
public interface OnItemClickListener {
void onItemClick(int position);
}
public interface OnItemLongClickListener {
boolean onItemLongClick(int position);
}
}
```
在 Activity 或者 Fragment 中,我们可以使用以下代码来设置点击事件:
```java
MyAdapter adapter = new MyAdapter(data);
adapter.setOnItemClickListener(new MyAdapter.OnItemClickListener() {
@Override
public void onItemClick(int position) {
// 处理点击事件
}
});
adapter.setOnItemLongClickListener(new MyAdapter.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(int position) {
// 处理长按事件
return true;
}
});
recyclerView.setAdapter(adapter);
```
阅读全文