RecyclerView的使用(二)点击事件
RecyclerView的实现了很多功能,但同时有很多功能是需要我们去实现的。RecyclerView的点击事件就需要我们自己去处理。方法就是通过Adapter的View 实现OnClickListener的监听。
基本的Adapter代码为
public class LinearAdapter extends RecyclerView.Adapter<LinearAdapter.MyViewHolder>{
private Context mContext;
private List<String> mDatas;
LinearAdapter(Context mContext,List<String> mDatas){
this.mContext = mContext;
this.mDatas = mDatas;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.item_linear,parent,false);
return new MyViewHolder(v);
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.tv.setText(mDatas.get(position));
}
@Override
public int getItemCount() {
return mDatas.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView tv;
public MyViewHolder(View itemView) {
super(itemView);
tv = (TextView) itemView.findViewById(R.id.adapter_linear_text);
}
}
}
首先我们需要定义一个接口
public interface OnItemClickListener{
//点击事件
void onItemClick(View v,int position);
//长按事件
void onItemLongClick(View v,int position);
}
//添加Set方法
public void setOnItemClickListener(OnItemClickListener mListener){
this.mListener = mListener;
}
在onBindViewHolder中添加点击事件回调
holder.tv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mListener.onItemClick(v, holder.getLayoutPosition());
}
});
holder.tv.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
mListener.onItemLongClick(v, holder.getLayoutPosition());
return false;
}
});
在Activity中使用
//设置Adapter
mAdapter = new LinearAdapter(this,mDatas);
mAdapter.setOnItemClickListener(new LinearAdapter.OnItemClickListener() {
@Override
public void onItemClick(View v, int position) {
Toast.makeText(ListViewActivity.this, "点击的位置是:"+position, Toast.LENGTH_SHORT).show();
}
@Override
public void onItemLongClick(View v, int position) {
Toast.makeText(ListViewActivity.this, "长点的是:"+ position, Toast.LENGTH_SHORT).show();
}
});
这样就实现了Item的点击事件
网友评论