class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> implements View.OnClickListener { private Context context; private List<String> list; public MyAdapter(Context context, List<String> list) { this.context = context; this.list = list; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = View.inflate(context, R.layout.item, null); ViewHolder holder=new ViewHolder(itemView); itemView.setOnClickListener(this); return holder; } @Override public void onBindViewHolder(ViewHolder holder, int position) { holder.text1.setText(list.get(position)); holder.itemView.setTag(position); } @Override public int getItemCount() { return list.size(); } @Override public void onClick(View view) { if (mItemClickListener!=null){ mItemClickListener.onItemClick((Integer) view.getTag()); } } class ViewHolder extends RecyclerView.ViewHolder { private final TextView text1; public ViewHolder(View itemView) { super(itemView); text1 = itemView.findViewById(R.id.text1); } } public interface OnItemClickListener{ void onItemClick(int position); } private OnItemClickListener mItemClickListener; //暴露一个方法方便给别的类去调用 public void setItemClickListener(OnItemClickListener itemClickListener) { mItemClickListener = itemClickListener; } }
RecyclerView 条目点击事件以及适配器
最新推荐文章于 2020-06-08 17:57:43 发布