android RecyclerView增加单击和双击,解决setOnTouchListener无效问题

产品的脑洞又双叒叕再一次大开,说到一个列表需要在原来上下滑动的基础上支持单击,双击,并且单击区分点击左侧和点击右侧,并且实现不同的功能(ps:幸好item里面没有点击事件,不然可能有点抓狂…)如下图:

android RecyclerView增加单击和双击,解决setOnTouchListener无效问题_第1张图片

列表用的RecyclerView,对于需求,只能给RecycerView设置setOnTouchListener监听,而点击和双击实现呢,肯定想到了用GestureDetector来实现,至于GestureDetector的介绍可以点击这里查看,该文章就不做过多解释,下面开说具体实现:

1.新建RecyclerView的onTouchListener类来实现View的OnTouchListener方法,并且创建GestureDetector,重写单击双击的方法,把OnTouchListener的onTouch方法交给GestureDetector来处理,

public class RecyclerViewOnTouchListener implements View.OnTouchListener {

    private Context mContext;
    private GestureDetector gestureDetector;
    private OnClickListener callback;

    public RecyclerViewOnTouchListener(Context context, OnClickListener listener){
        if(context == null){
            return;
        }
        this.mContext = context;
        this.callback = listener;
        gestureDetector = new GestureDetector(mContext, new GestureDetector.SimpleOnGestureListener() {

            /**
             * 单击
             * @param e
             * @return
             */
            @Override
            public boolean onSingleTapConfirmed(MotionEvent e) {

                if(callback != null){
                    callback.onSingleClick((int)e.getX(), (int)e.getY());
                }

                return super.onSingleTapConfirmed(e);
            }

            /**
             * 双击
             * @param e
             * @return
             */
            @Override
            public boolean onDoubleTap(MotionEvent e) {
                if(callback != null){
                    callback.onDoubleClick();
                }
                return super.onDoubleTap(e);
            }
        });
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return gestureDetector.onTouchEvent(event);
    }


    interface OnClickListener{
        /**
         * 单击
         * @param touthX 点击的x坐标
         * @param touchY 点击的y坐标
         */
        void onSingleClick(int touthX, int touchY);

        /**
         * 双击
         */
        void onDoubleClick();
    }
}

然后设置给RecyclerView就可以了

rvList.setOnTouchListener(RecyclerViewOnTouchListener(this, object : RecyclerViewOnTouchListener.OnClickListener {

            override fun onSingleClick(touthX: Int, touchY: Int) {

                val halfWidth = (rvList?.width ?: 0) / 2

                if(halfWidth > touthX){
                    Toast.makeText(this@MainActivity, "点击到了左侧", Toast.LENGTH_SHORT).show()
                }else{
                    Toast.makeText(this@MainActivity, "点击到了右侧", Toast.LENGTH_SHORT).show()
                }
            }

            override fun onDoubleClick() {
                Toast.makeText(this@MainActivity, "纳尼,竟然被双击了", Toast.LENGTH_SHORT).show()
            }
        }))

代码:点击此处

你可能感兴趣的:(Android)