如何给recyclerview的item监听

 我来答
xiangjuan314
推荐于2018-04-07 · TA获得超过3.3万个赞
知道大有可为答主
回答量:2.9万
采纳率:0%
帮助的人:2907万
展开全部
RecyclerView的2种监听方式

NO.1:在自定义适配器的ViewHolder里面写监听事件
//RecyclerView适配器
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context mContext;
private LayoutInflater mLayoutInflater;
private String[] mCityName;

public RecyclerViewAdapter(Context mContext) {
this.mContext = mContext;
mLayoutInflater = LayoutInflater.from(mContext);
mCityName = mContext.getResources().getStringArray(R.array.city_name);
}

//创建新ViewHolder,被LayoutManager所调用
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new RecyclerViewViewHolder(mLayoutInflater.inflate(R.layout.item_text, parent, false));
}

//将数据与界面进行绑定的操作
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
((RecyclerViewViewHolder) holder).mTextView.setText(mCityName[position]);
}

//获取数据的数量
@Override
public int getItemCount() {
return mCityName == null ? 0 : mCityName.length;
}

//自定义的ViewHolder,持有每个Item的的所有界面元素
public class RecyclerViewViewHolder extends RecyclerView.ViewHolder {
TextView mTextView;

public RecyclerViewViewHolder(View itemView) {
super(itemView);
mTextView = (TextView) itemView.findViewById(R.id.tv_city);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ToastUtil.show(mContext, getPosition() + "");
}
});
}
}
}

NO.2:封装个监听类
public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
private OnItemClickListener mListener;

public interface OnItemClickListener {
public void onItemClick(View view, int position);
}

GestureDetector mGestureDetector;

public RecyclerItemClickListener(Context context, OnItemClickListener listener) {
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
}

@Override public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
View childView = view.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
mListener.onItemClick(childView, view.getChildPosition(childView));
return true;
}
return false;
}

@Override public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) { }
}

使用方法:
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
ToastUtil.show(OneActivity.this, position + "");
}
}));
本回答被网友采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式