Android滑动冲突解决方案

外部拦截法

重写父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滑动冲突解决方案)