美文网首页
Android滑动冲突解决方案

Android滑动冲突解决方案

作者: Zachary46 | 来源:发表于2021-04-16 11:32 被阅读0次

    外部拦截法

    重写父View onInterceptTouchEvent方法就行:

        float latestX;
        float latestY;
    
        @Override
        public boolean onInterceptTouchEvent(MotionEvent ev) {
            boolean isIntercept = false;
    
            switch (ev.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    isIntercept = false;
                    break;
                case MotionEvent.ACTION_MOVE:
                    float dx = Math.abs(ev.getRawX() - latestX);
                    float dy = Math.abs(ev.getRawY() - latestY);
                    if (dx > dy) {
                        isIntercept = true;
                    } else {
                        isIntercept = false;
                    }
                    break;
                case MotionEvent.ACTION_UP:
                    isIntercept = false;
                    break;
            }
            latestX = ev.getRawX();
            latestY = ev.getRawY();
            return isIntercept;
        }
    

    内部拦截法

    父View重写onInterceptTouchEvent方法:

       @Override
        public boolean onInterceptTouchEvent(MotionEvent ev) {
            boolean isIntercept = false;
            if (ev.getAction() == MotionEvent.ACTION_DOWN) {
                isIntercept = false;
            } else {
                isIntercept = true;
            }
            return isIntercept;
        }
    

    然后子View重写dispatchTouchEvent方法:

       float latestX;
        float latestY;
    
        @Override
        public boolean dispatchTouchEvent(MotionEvent ev) {
    
            switch (ev.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    getParent().requestDisallowInterceptTouchEvent(true);
                    break;
                case MotionEvent.ACTION_MOVE:
                    float dx = Math.abs(ev.getRawX() - latestX);
                    float dy = Math.abs(ev.getRawY() - latestY);
                    if (dx > dy) {
                        getParent().requestDisallowInterceptTouchEvent(false);
                    }
                    break;
                case MotionEvent.ACTION_UP:
                    break;
                latestX = ev.getRawX();
                latestY = ev.getRawY();
                return super.dispatchTouchEvent(ev);
            }
    

    相关文章

      网友评论

          本文标题:Android滑动冲突解决方案

          本文链接:https://www.haomeiwen.com/subject/klfelltx.html