recyclerview点击事件代码
时间: 2023-11-12 12:31:36 浏览: 72
以下是RecyclerView点击事件的代码:
1. 在RecyclerView的Adapter中,定义一个接口来处理点击事件:
public interface OnItemClickListener {
void onItemClick(int position);
}
2. 在ViewHolder中,为每个item设置点击事件:
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
OnItemClickListener listener;
public MyViewHolder(View itemView, OnItemClickListener listener) {
super(itemView);
this.listener = listener;
itemView.setOnClickListener(this);
}
@Override
public void onClick(View view) {
listener.onItemClick(getAdapterPosition());
}
}
3. 在Adapter中,实现接口并将点击事件传递给Activity或Fragment:
public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {
private List<String> dataList;
private OnItemClickListener listener;
public MyAdapter(List<String> dataList, OnItemClickListener listener) {
this.dataList = dataList;
this.listener = listener;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout, parent, false);
return new MyViewHolder(view, listener);
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.textView.setText(dataList.get(position));
}
@Override
public int getItemCount() {
return dataList.size();
}
}
4. 在Activity或Fragment中,实现接口并处理点击事件:
public class MainActivity extends AppCompatActivity implements MyAdapter.OnItemClickListener {
private RecyclerView recyclerView;
private MyAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
List<String> dataList = new ArrayList<>();
dataList.add("Item 1");
dataList.add("Item 2");
dataList.add("Item 3");
adapter = new MyAdapter(dataList, this);
recyclerView.setAdapter(adapter);
}
@Override
public void onItemClick(int position) {
Toast.makeText(this, "Item clicked at position " + position, Toast.LENGTH_SHORT).show();
}
}
阅读全文