RecyclerView导致父控件点击事件无效

先说下现象,列表item布局中 , 包含recyclerView, item点击 recyclerView 部分时,点击事件无效

recyclerView.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {
            myLayout.performClick();  //模拟父控件的点击
        }
        return false;
    }
});

一开始这样改的,可以滑动列表时,容易误触点击事件,后来改良下

recyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        //float DownX
                        downX = event.getX();
                        //float DownY
                        downY = event.getY();
                        moveX = 0;
                        moveY = 0;
                        //long currentMS     获取系统时间
                        currentMS = System.currentTimeMillis();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        moveX += Math.abs(event.getX() - downX);//X轴距离
                        moveY += Math.abs(event.getY() - downY);//y轴距离
                        downX = event.getX();
                        downY = event.getY();
                        break;
                    case MotionEvent.ACTION_UP:
                        long moveTime = System.currentTimeMillis() - currentMS;//移动时间
                        //判断点击还是滑动
                        if (moveTime < 200 || (moveX < 20 && moveY < 20)) {
                            listener.onItemClick(item);
                            return true; //不再执行后面的事件
                        }
                        break;
                }
                return false;
            }
        });

至此完美解决问题.

第二种解决方法(同事想出来的)

recyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return parent.onTouchEvent(event);
            }
        });

这样更简单,子布局的recycleview把点击事件再传给父布局,亲测可行

 

你可能感兴趣的:(RecyclerView导致父控件点击事件无效)