RecyclerView 是Android L版本中新添加的一个用来取代ListView的SDK,它的灵活性与可替代性比ListView更好。RecyclerView的强大这里就不说了。
RecyclerView使用有点小小的不足,就是没有像ListView那样提供ClickListener和LongClickListener方法,需要我们手动去添加。这并不影响它的灵活性。
要实现RecyclerView的ClickListener和LongClickListener方法,我们可以用这种方式来实现:
在适配器adapter中定义接口,然后在onBindViewHolder中去为holder.itemView去设置相应的监听,最后回调我们设置的监听即可。
public class AikaifaAdapter extends RecyclerView.Adapter<AikaifaAdapter.AikaifaViewHolder> {
private Context mConttext;
private List<ShopCar.CarList> data;
//定义接口
public interface OnItemClickListener {
void onItemClick(View view, int position);
void onItemLongClick(View view, int position);
}
private OnItemClickListener mOnItemClickListener;
public AikaifaAdapter(Context context, List<ShopCar.CarList> data) {
this.mConttext = context;
this.data = data;
}
public void setOnItemClickListener(OnItemClickListener mOnItemClickListener) {
this.mOnItemClickListener = mOnItemClickListener;
}
@Override
public AikaifaAdapter.AikaifaViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
view = LayoutInflater.from(mConttext).inflate(R.layout.item_shopcart, parent, false);
return new AikaifaAdapter.AikaifaViewHolder(view);
}
@Override
public void onBindViewHolder(final AikaifaViewHolder holder, final int position) {
holder.tv.setText(data.get(position).getProductName());
if (mOnItemClickListener != null) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int pos = holder.getLayoutPosition();
mOnItemClickListener.onItemClick(holder.itemView, position);
}
});
holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
int pos = holder.getLayoutPosition();
mOnItemClickListener.onItemLongClick(holder.itemView, pos);
return false;
}
});
}
}
@Override
public int getItemCount() {
int count = (data == null ? 0 : data.size());
return count;
}
class AikaifaViewHolder extends RecyclerView.ViewHolder {
private TextView tv;
public AikaifaViewHolder(View view) {
super(view);
tv = (TextView) view.findViewById(R.id.tv_item_shopcart_shopname);
}
}
这样调用
mAdapter.setOnItemClickLitener(new OnItemClickLitener() {
@Override
public void onItemClick(View view, int position) {
//点击事件
}
@Override
public void onItemLongClick(View view, int position) {
//长按事件
}
});
这样就完成了RecyclerView的点击事件了。
[END]
我是洪生鹏,热衷旅行、写作,目前过着白天到工地搬砖、晚上写故事的生活。希望今天的文章对你有帮助。坚持日更,一般会在晚上10点发文,欢迎交流。
如果你喜欢今天的文章,特意为你推荐: