RecyclerView中没有提供OnItemClick这样的事件,自己封装了一个
abstract public class RecyclerViewOnItemClickListener extends RecyclerView.SimpleOnItemTouchListener{
abstract protected void onItemClick(View view, int position);
abstract protected void onItemLongClick(View view, int position);
private GestureDetectorCompat mGestureDetectorCompat;
public RecyclerViewOnItemClickListener(RecyclerView recyclerView)
{
mGestureDetectorCompat = new GestureDetectorCompat(recyclerView.getContext(), new GestureDetector.OnGestureListener() {
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
View childView = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (childView != null) {
onItemClick(childView, recyclerView.getChildAdapterPosition(childView));
}
return true;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
View childView = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (childView != null) {
onItemLongClick(childView, recyclerView.getChildAdapterPosition(childView));
}
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
});
}
@Override
public void onTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) {
if (!mGestureDetectorCompat.onTouchEvent(e))
{
super.onTouchEvent(rv, e);
}
}
@Override
public boolean onInterceptTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) {
if (!mGestureDetectorCompat.onTouchEvent(e))
{
return super.onInterceptTouchEvent(rv, e);
}
return true;
}
}
使用的时候非常方便
recyclerView.addOnItemTouchListener(new RecyclerViewOnItemClickListener(recyclerView){
@Override
protected void onItemClick(View view, int position) {
}
@Override
protected void onItemLongClick(View view, int position) {
}
});