Android

RecyclerView之添加Item的点击事件

2019-03-04  本文已影响863人  12313凯皇

在网上百度到了一些方法,基本大同小异,于是根据自己的理解实现了这个功能。

public class MytAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>{

  ...
  //私有属性
  private OnItemClickListener onItemClickListener = null;

  //setter方法
  public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
      this.onItemClickListener = onItemClickListener;
  }

  //回调接口
  public interface OnItemClickListener {
      void onItemClick(View v, Note note, int position);
  }

  ...

}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        
    //实现点击效果
    holder.itemView.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
              if (onItemClickListener != null) {
                onItemClickListener.onItemClick(v, note, position);
              }
          }
    });
}
MyAdapter.setOnItemClickListener(new MyAdapter.OnItemClickListener() {
      @Override
      public void onItemClick(View v, Note note, int position) {
                
      }
});
上一篇下一篇

猜你喜欢

热点阅读