Android 判断触摸点是否在某个view内部,解决子childView与parentView的touch事件冲突

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010886975/article/details/70638408

事件冲突在触摸事件经常发生,这里记一个解决子view与parent的touch事件冲突的小方法:
原理,对触摸点进行位置判断,是否在目标View内部。
第一步:判断位置

private boolean isTouchPointInView(View targetView, int xAxis, int yAxis) {
            if (targetView== null) {
                return false;
            }
            int[] location = new int[2];
            targetView.getLocationOnScreen(location);
            int left = location[0];
            int top = location[1];
            int right = left + targetView.getMeasuredWidth();
            int bottom = top + targetView.getMeasuredHeight();
            if (yAxis >= top && yAxis <= bottom && xAxis >= left
                    && xAxis <= right) {
                return true;
            }
            return false;
     }

第二步:在parentView中,进行事件拦截

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        int x = (int) ev.getRawX();
        int y = (int) ev.getRawY();
        if (isTouchPointInView(targetView, x, y)) {
        // insided,do somethings you like
            return super.dispatchTouchEvent(ev);
        }else{
        // outsided,do somethings you like
            return super.dispatchTouchEvent(ev);
        }
    }

猜你喜欢

转载自blog.csdn.net/u010886975/article/details/70638408