看鸿洋公众号早上推的文章,自己敲了一遍。。。
自从RecyclerView发布以来,由于其高度的可交互性被广泛使用。但是RecyclerView确没有像ListView一样提供onItemClickListener却让人比较难过,网上搜索了一番有不少解决方案,但是其本质都是通过给每个item添加onClickListener来模仿一个伪onItemClickListener,这种为每个item添加点击监听的解决方案不用多想也知道是浪费性能的方法。能不能像ListView那样使用一个监听解决问题呢?
查阅RecyclerView的api发现虽然没有提供onItemClickListener但是提供了addOnItemTouchListener方法:
RecyclerView.addOnItemTouchListener(OnItemTouchListener listener)
既然可以添加触摸监听,那么我们完全可以获取触摸手势来识别点击事件,然后通过触摸坐标来判断点击的是哪一个item。
直接上代码:
package com.glodon.reviewdemo;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
/**
* Created by liyx-k on 2016/5/12.
*/
public abstract class OnRecyclerItemClickListener implements RecyclerView.OnItemTouchListener{
private final RecyclerView recyclerView;
private final GestureDetectorCompat mGestureDetector;
public OnRecyclerItemClickListener(RecyclerView recyclerView){
this.recyclerView=recyclerView;
mGestureDetector = new GestureDetectorCompat(recyclerView.getContext(),new ItemTouchHelperGestureListener());
}
@Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
mGestureDetector.onTouchEvent(e);
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
mGestureDetector.onTouchEvent(e);
return false;
}
public abstract void onItemClick(RecyclerView.ViewHolder viewHolder);
public abstract void onItemLOngClick(RecyclerView.ViewHolder viewHolder);
private class ItemTouchHelperGestureListener extends GestureDetector.SimpleOnGestureListener {
public boolean onSingleTapUp(MotionEvent event){
View child = recyclerView.findChildViewUnder(event.getX(), event.getY());
if (child != null){
RecyclerView.ViewHolder viewHolder = recyclerView.getChildViewHolder(child);
onItemClick(viewHolder);
}
return true;
}
public void onLongPress(MotionEvent event){
View child = recyclerView.findChildViewUnder(event.getX(), event.getY());
if (child != null){
RecyclerView.ViewHolder viewHolder = recyclerView.getChildViewHolder(child);
onItemLOngClick(viewHolder);
}
}
}
}
在代码里直接引用就行: