Android滑动冲突解决方案

2021-04-19 18:00:44 浏览数 (1)

外部拦截法

重写父View onInterceptTouchEvent方法就行:

代码语言:javascript复制
    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方法:

代码语言:javascript复制
   @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        boolean isIntercept = false;
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            isIntercept = false;
        } else {
            isIntercept = true;
        }
        return isIntercept;
    }

然后子View重写dispatchTouchEvent方法:

代码语言:javascript复制
   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);
        }

0 人点赞