Open LiangGaoUser opened 4 years ago
在recycleViewAdapter中设置两个自定义的接口
public interface OnItemClickListener{ void onItemClick(View view,int position); } public interface OnItemLongClickListener{ void onItemLongClick(View view,int position); } public void setOnItemClickListener(OnItemClickListener onItemClickListener){ this.onItemClickListener=onItemClickListener; } public void setOnItemLongClickListener(OnItemLongClickListener onItemLongClickListener){ this.onItemLongClickListener=onItemLongClickListener; }
在onBindViewHolder方法中判断activity是否设置了监听,回调
//判断是否在activity中设置监听,回调 if(onItemClickListener!=null){ myViewHolder.itemView.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { int position=myViewHolder.getLayoutPosition(); onItemClickListener.onItemClick(myViewHolder.itemView,position); } }); } if(onItemLongClickListener!=null){ myViewHolder.itemView.setOnLongClickListener(new View.OnLongClickListener(){ @Override public boolean onLongClick(View v) { int position=myViewHolder.getLayoutPosition(); onItemLongClickListener.onItemLongClick(myViewHolder.itemView,position); return true; } }); }
在activity中给适配器set方法设置实现接口的匿名内部类,然后实现接口中的方法
recyclerViewAdapter.setOnItemClickListener(new RecyclerViewAdapter.OnItemClickListener() { @Override public void onItemClick(View view, int position) { Toast.makeText(getContext(),"点击了recycleview第"+position+"个位置",Toast.LENGTH_LONG).show(); } });
在recycleViewAdapter中设置两个自定义的接口
在onBindViewHolder方法中判断activity是否设置了监听,回调
在activity中给适配器set方法设置实现接口的匿名内部类,然后实现接口中的方法