由于RecycleView中没有点击事件,所以还要手动添加,今天给大家写一下在XRecycleView或RecycleView中添加点击事件
天加点击事件要用到接口回调,所以,还是要吧接口回调给学好啊,用的地方还是挺多的。
首先,说一下理论吧,在展示完数据之后,在适配器中,设置一个内部接口,手动添加点击事件,添加接口的构造方法,在ManActivity中调用,这个就类似于就扣回调了
接下来说一说代码:
// 设置点击事件的接口,利用接口回调,来完成点击事件
public interface OnItemClickLitener {
void onItemClick(View view, int position);
void onItemLongClick(View view, int position);
}
private OnItemClickLitener mOnItemClickLitener;
public void setOnItemClickLitener(OnItemClickLitener mOnItemClickLitener) {
this.mOnItemClickLitener = mOnItemClickLitener;
}
在onBindViewHolder放发中:
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int pos = holder.getLayoutPosition();
mOnItemClickLitener.onItemClick(holder.itemView, pos);
}
});
holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
int pos = holder.getLayoutPosition();
mOnItemClickLitener.onItemLongClick(holder.itemView, pos);
return false;
}
});
点击事件在这里就写完了,接下来在主函数中调用就可以了:
adapter = new HomeAdapter(list,MainActivity.this);
adapter.setOnItemClickLitener(new HomeAdapter.OnItemClickLitener() {
@Override
public void onItemClick(View view, int position) {
Toast.makeText(MainActivity.this, position+"点击", Toast.LENGTH_SHORT).show();
}
@Override
public void onItemLongClick(View view, int position) {
Toast.makeText(MainActivity.this, position+"长安", Toast.LENGTH_SHORT).show();
}
});
xRecyclerView.setAdapter(adapter);
在调用时,要注意在初始化适配器之后添加点击事件,否则数据不会显示的。
谢谢~~~~~