具体实现Item中的某一个Button监听,而不是整个item的监听
-
首先在自定义Adapter中进行Button监听,以及传递一个回调接口(用于具体的动作)
定义一个回调接口
public interface OnItemClickListener {
void onItemClick(int position, View v);
}
在自定义Adapter类的操作
获得从外部传入的回调接口
public void setOnItemClickListener(OnItemClickListener onItemClickListener){
this.mOnItemClickListener = onItemClickListener;
}
在ViewHolder中设置Button监听,并且调用回调函数
static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
OnItemClickListener mOnItemClickListener;
Button btn;
public ViewHolder(View view){
super(view);
cardView = (CardView)view;
btn.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if(mOnItemClickListener != null){
mOnItemClickListener.onItemClick(getAdapterPosition(),v);
}
}
}
绑定adapter与viewholder的OnItemClickListener
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if(mContext == null){
mContext = parent.getContext();
}
view = LayoutInflater.from(mContext).inflate(R.layout.goods_item,parent,false);
ViewHolder viewHolder = new ViewHolder(view);
viewHolder.mOnItemClickListener = mOnItemClickListener;
return viewHolder;
}
-
在activity中创建一个具体的回调函数类,并传入给adapter
adapter.setOnItemClickListener(onItemClickListener);
recyclerView.setAdapter(adapter);
private OnItemClickListener onItemClickListener = new OnItemClickListener() {
@Override
public void onItemClick(int position, View v) {
if(v.getId() == R.id.button){
//具体的动作
}
}
};
结束了,第一次写,写得不好多多包涵