主要入手点:自定的Adapter中自定义的ViewHolder,持有每个Item的的所有界面元素。Item的点击事件可通过view的OnClick来实现。如果我们要在Activity中监听到item的点击,需要在Adapter中定义一个回调接口。如下:
public interface OnItemClickListener{
void onItemClick(View view, int position);//该方法回调到activity或fragment中做相应操作
}
继续在Adapter中实例出一个OnItemClickListener itemClickListener,当activity中new出一个adapter时,调用setOnItemClickListener方法,
就传入一个OnItemClickListener。
private OnItemClickListener itemClickListener;
public void setOnItemClickListener(OnItemClickListener onItemClickListener ){
this.itemClickListener=onItemClickListener;
}
接下来在ViewHolder类中将adapter的itemClickListener传入到ViewHolder构造方法中,我们知道ViewHolder本可以实现view的点击事件,在OnClick中我们便实现了回调。
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView mTextView;
private OnItemClickListener mitemClickListener;
public ViewHolder(View view,OnItemClickListener itemClickListener) {
super(view);
mTextView = (TextView) view.findViewById(R.id.area_item_tv);
this.mitemClickListener=itemClickListener;
view.setOnClickListener(this);
}
@Override
public void onClick(View view) {
if (mitemClickListener != null) {
mitemClickListener.onItemClick(view,getPosition());
}
}
}
那么在activity或fragment中
adapter=new MyAdapter(dataList);
recyclerView.setAdapter(adapter);
adapter.setOnItemClickListener(new MyAdapter.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
//定义相应的事件逻辑
}
});