今天我们只说一个问题,就是RecyclerView添加Item点击事件,我们之前在使用Listview的时候,Listview提供了很方便的OnItemClickListener事件回调:
ListView listView = new ListView(this);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
...
}
});
但是在RecyclerView中并未提供这个方法,虽然RecyclerView提供了addOnItemTouchListener回调,但是它并不是我们想要的Click事件回调,所以我们需要自己实现一个OnItemClickListener事件,具体流程
1、自定义一个OnItemClickListener回调接口
public interface OnItemClickListener {
/**
* DyneModel 是对应Item的数据绑定对象
*/
void onItemClick(DyneModel dyneModel);
}
2、在自定义Adapter的构造方法参数中添加OnItemClickListener
private OnItemClickListener iDyneListener;
public DyneAdapter(Context context, OnItemClickListener iDyneListener) {
this.context = context;
this.iDyneListener = iDyneListener;
}
使用的地方调用:
DyneAdapter dyneAdapter = new DyneAdapter(this, new OnItemClickListener() {
@Override
public void onItemClick(DyneModel dyneModel) {
}
});
当然我们不一定需要在构造方法中添加OnItemClickListener,而是在自定义Adapter中添加一个传入的方法
private OnItemClickListener iDyneListener;
public void setOnItemClickListener(OnItemClickListener iDyneListener){
this.iDyneListener = iDyneListener;
}
使用的地方调用:
DyneAdapter dyneAdapter = new DyneAdapter(this);
dyneAdapter.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(DyneModel dyneModel) {
......
}
});
3、在自定义ViewHolder中这个处理
class DyneHolder extends RecyclerView.ViewHolder {
private View itemView;
public DyneHolder(View itemView) {
super(itemView);
this.itemView = itemView;
}
}
4、自定义Adapter中先实现OnClickListener事件
public class DyneAdapter extends RecyclerView.Adapter<DyneAdapter.DyneHolder> implements View.OnClickListener {
@Override
public void onClick(View v) {
iDyneListener.onItemClick(dyneModels.get((Integer) v.getTag()));
}
}
5、在自定义adapter中的onBindViewHolder方法中获取Item点击事件:
@Override
public void onBindViewHolder(DyneHolder holder, final int position) {
holder.itemView.setTag(position);
holder.itemView.setOnClickListener(this);
}
这就是完整的RecyclerView添加Item点击事件流程,其实流程很简单,感谢!