可以通过自定义接口的方式实现
public interfaceOnItemClickListener{
voidonItemClick(Viewview,intposition);
}
public interfaceonLongItemClickListener{
voidonLongItemClick(Viewview,intpostion);
}
自定义接口的目的是为了传入我们想传的参数
public abstract classBaseAdapter extendsRecyclerView.Adapter{
private OnItemClickListenermItemClickListener;
private onLongItemClickListenermLongItemClickListener;
@Override
public voidonBindViewHolder(BaseViewHolderholder,final intposition) {
convert(mContext,holder,mDatas.get(position));
if(mItemClickListener!= null) {
holder.mItemView.setOnClickListener(newView.OnClickListener() {
@Override
public voidonClick(Viewv) {
mItemClickListener.onItemClick(v,position);
}
});
}
if(mLongItemClickListener!= null) {
holder.itemView.setOnLongClickListener(newView.OnLongClickListener() {
@Override
public booleanonLongClick(Viewv) {
mLongItemClickListener.onLongItemClick(v,position);
return true;
}
});
}
}
public interfaceOnItemClickListener{
voidonItemClick(Viewview,intposition);
}
public interfaceonLongItemClickListener{
voidonLongItemClick(Viewview,intpostion);
}
public voidsetOnItemClickListener(OnItemClickListenerlistener) {
this.mItemClickListener=listener;
}
public voidsetonLongItemClickListener(onLongItemClickListenerlistener) {
this.mLongItemClickListener=listener;
}
}
原理是给itemView(当前的子view)添加点击事件,在点击事件的方法里写上自定义的接口