RecyclerView点击事件

import android.support.v4.view.GestureDetectorCompat;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;

/**
 * 
 *  名称:RecyclerItemClickListener
 *  作用:
 *  描述:
 *  作者:pczhu
 *  创建时间: 2017/6/9 下午2:26
 *  版本:V1.0
 *  修改历史:
 *  
*/ public class RecyclerItemClickListener extends RecyclerView.SimpleOnItemTouchListener { private OnItemClickListener clickListener; private GestureDetectorCompat gestureDetector; //v4 兼容包中 public interface OnItemClickListener { /** * 点击时回调 * * @param view 点击的View * @param position 点击的位置 */ void onItemClick(View view, int position); /** * 长点击时回调 * * @param view 点击的View * @param position 点击的位置 */ void onItemLongClick(View view, int position); } public RecyclerItemClickListener(final RecyclerView recyclerView, OnItemClickListener listener) { this.clickListener = listener; gestureDetector = new GestureDetectorCompat(recyclerView.getContext(), new GestureDetector.SimpleOnGestureListener() { @Override public boolean onSingleTapUp(MotionEvent e) { //找到点击位置对应的recyclerViewItem布局 View childView = recyclerView.findChildViewUnder(e.getX(), e.getY()); if (childView != null && clickListener != null ) { //回调item对象以及在recyclerview中的位置 clickListener.onItemClick(childView, recyclerView.getChildAdapterPosition(childView)); return true; } return super.onSingleTapUp(e); } @Override public void onLongPress(MotionEvent e) { //找到点击位置对应的recyclerViewItem布局 View childView = recyclerView.findChildViewUnder(e.getX(), e.getY()); if (childView != null && clickListener != null) { //回调item对象以及在recyclerview中的位置 clickListener.onItemLongClick(childView, recyclerView.getChildAdapterPosition(childView)); } } }); } @Override public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) { //拦截相关事件交给gestureDetector对象处理。 if(gestureDetector.onTouchEvent(e)){ return true; } return false; } }

你可能感兴趣的:(RecyclerView点击事件)