专栏首页胡飞洋的Android进阶View事件分发、滑动冲突 详解

View事件分发、滑动冲突 详解

目录

一、事件分发

1、事件传递规则

2、源码分析

1)Activity的分发过程:

2)顶级View(ViewGroup)的分发过程:分发规则的伪代码来源的详细说明

3)view的处理过程:主要是onTouchListener、OnTouchEvent、onClick的关系

二、滑动冲突

1、冲突场景

2、解决原理

View的事件分发,指的是 在多层级ViewGroup/View中对触摸事件的分发。触摸事件即MotionEvent,系统要把它传递给具体的view取处理。 事件序列,从Down开始,到多个Move,再到Up结束,就是一个事件序列。

一、事件分发

1、事件传递规则

事件分发主要3个方法:

  • public boolean dispatchTouchEvent(MotionEvent ev),负责事件的传递分发,事件到达view时一定回调此方法。返回值表示是否消费此事件,受onTouchEvent和子view的dispatchTouchEvent返回值影响。
  • public boolean onInterceptTouchEvent(MotionEvent ev),用于判断是否拦截事件,也是返回值的含义。在dispatchTouchEvent内部调用。view拦截了某个事件,那后续这一事件序列都会默认拦截,不再调用此方法
  • public boolean onTouchEvent(MotionEvent event),用于处理事件,返回值表示是否消费此事件。

在dispatchTouchEvent内部调用。如果不消耗某一事件,那当前view不再接受同一事件序列的事件。注意,如果设置了onTouchListener且onTouch返回值是true,那么不会调用onTouchEvent(会给父view处理)onTouchEvent中发现设置了onClickListener那onCLick会被调用

三者关系:事件到达view时,会调用dispatchTouchEvent,然后内部调用onInterceptTouchEvent判断是否拦截,如果不拦截就调用子view的dispatchTouchEvent。用伪代码表示:

public boolean dispatchTouchEvent(MotionEvent event){
        boolean consumed;
        if (onIntercepterTouchEvent(event)){
            consumed = onTouchEvent(event);
        }else {
            consumed = child.dispatchTouchEvent(event);
        }

        return consumed;
    }

事件发生时,传递顺序是:Activity-Window-View。如果所有activity的所有子View都不处理,那么最终Activity的onTouchEvent会被调用。

另外几点规则:

  1. ViewGroup默认不拦截任何事件。即onInterceptTouchEvent方法返回false
  2. View没有onInterceptTouchEvent()
  3. View的onTouchEvent默认会消耗事件(返回True),除非它是不可点击的——-clickable 和 longClickable同时为false.注意:View的longClickable默认都为false,clickable要根据控件属性判断。
  4. View的enable属性不影响onTouchEvent的默认返回值。(哪怕是disable)
  5. 事件重视先传递给父元素,然后由父元素分发给子View.通过requestDisallowIntercept()分发可以在子元素中干预父元素的事件分发过程,但是ACTION_DOWN事件除外。

2、源码分析

1)Activity的分发过程:

public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            onUserInteraction();
        }
        //调用window的superDispatchTouchEvent来分发。(实际window只有一个实现PhoneWindow)
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        //如果window内所有view没有消费,就会走acticity的onTouchEvent
        return onTouchEvent(ev);
    }

看PhoneWindow:

// This is the top-level view of the window, containing the window decor.
    private DecorView mDecor;

@Override
    public boolean superDispatchTouchEvent(MotionEvent event) {
        //mDecor是DecorView
        return mDecor.superDispatchTouchEvent(event);
    }

看DecorView:

public boolean superDispatchTouchEvent(MotionEvent event) {
        return super.dispatchTouchEvent(event);
    }

继续跟就到了ViewGroup的dispatchTouchEvent。DecorView内部的子View实际就是StatusBar、ActionBar、ContengView这些。

2)顶级View(ViewGroup)的分发过程:分发规则的伪代码来源的详细说明

@Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        ...

        boolean handled = false;
        if (onFilterTouchEventForSecurity(ev)) {
            final int action = ev.getAction();
            final int actionMasked = action & MotionEvent.ACTION_MASK;

            // Handle an initial down.
            // 事件DOWN时会清除 子view的 "不允许父view拦截"的flag。因为Down事件是事件序列的开始,一定会询问本身是否拦截。
            if (actionMasked == MotionEvent.ACTION_DOWN) {
                // Throw away all previous state when starting a new touch gesture.
                // The framework may have dropped the up or cancel event for the previous gesture
                // due to an app switch, ANR, or some other state change.
                cancelAndClearTouchTargets(ev);
                resetTouchState();
            }

            // Check for interception.
            final boolean intercepted;
            //是Down 或者 MOVE、UP但没有拦截DOWN让子View处理了(mFirstTouchTarget != null)
            if (actionMasked == MotionEvent.ACTION_DOWN
                    || mFirstTouchTarget != null) {
                final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
                if (!disallowIntercept) {
                    //如果子View没有不允许拦截,就正常询问自己是否拦截
                    intercepted = onInterceptTouchEvent(ev);
                    ev.setAction(action); // restore action in case it was changed
                } else {
                    //如果子View设置了不允许拦截,就不拦截
                    intercepted = false;
                }
            } else {
                // There are no touch targets and this action is not an initial down
                // so this view group continues to intercept touches.
                //不是Down且子view没有处理,就是说本身拦截了DOWN,那后续的MOVE、UP就不再调用onInterceptTouchEvent询问,直接拦截。
                intercepted = true;
            }

            // If intercepted, start normal event dispatch. Also if there is already
            // a view that is handling the gesture, do normal event dispatch.
            if (intercepted || mFirstTouchTarget != null) {
                ev.setTargetAccessibilityFocus(false);
            }

            // Check for cancelation.
            final boolean canceled = resetCancelNextUpFlag(this)
                    || actionMasked == MotionEvent.ACTION_CANCEL;

            // Update list of touch targets for pointer down, if needed.
            final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;
            TouchTarget newTouchTarget = null;
            boolean alreadyDispatchedToNewTouchTarget = false;

            //如果没有拦截
            if (!canceled && !intercepted) {

                ...

                if (actionMasked == MotionEvent.ACTION_DOWN
                        || (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)
                        || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
                    final int actionIndex = ev.getActionIndex(); // always 0 for down
                    final int idBitsToAssign = split ? 1 << ev.getPointerId(actionIndex)
                            : TouchTarget.ALL_POINTER_IDS;

                    // Clean up earlier touch targets for this pointer id in case they
                    // have become out of sync.
                    removePointersFromTouchTargets(idBitsToAssign);

                    final int childrenCount = mChildrenCount;
                    if (newTouchTarget == null && childrenCount != 0) {
                        final float x = ev.getX(actionIndex);
                        final float y = ev.getY(actionIndex);
                        // Find a child that can receive the event.
                        // Scan children from front to back.
                        final ArrayList<View> preorderedList = buildTouchDispatchChildList();
                        final boolean customOrder = preorderedList == null
                                && isChildrenDrawingOrderEnabled();
                        final View[] children = mChildren;

                        //就遍历子view
                        for (int i = childrenCount - 1; i >= 0; i--) {
                            final int childIndex = getAndVerifyPreorderedIndex(
                                    childrenCount, i, customOrder);
                            final View child = getAndVerifyPreorderedView(
                                    preorderedList, children, childIndex);

                            ...

                            //判断子view能否接受事件:是否在播动画、是否点击在区域内
                            if (!canViewReceivePointerEvents(child)
                                    || !isTransformedTouchPointInView(x, y, child, null)) {
                                ev.setTargetAccessibilityFocus(false);
                                continue;
                            }

                            newTouchTarget = getTouchTarget(child);
                            if (newTouchTarget != null) {
                                // Child is already receiving touch within its bounds.
                                // Give it the new pointer in addition to the ones it is handling.
                                newTouchTarget.pointerIdBits |= idBitsToAssign;
                                break;
                            }

                            resetCancelNextUpFlag(child);

                            //child不为空就会调child.dispatchTouchEvent(event)
                            if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
                                // Child wants to receive touch within its bounds.
                                mLastTouchDownTime = ev.getDownTime();
                                if (preorderedList != null) {
                                    // childIndex points into presorted list, find original index
                                    for (int j = 0; j < childrenCount; j++) {
                                        if (children[childIndex] == mChildren[j]) {
                                            mLastTouchDownIndex = j;
                                            break;
                                        }
                                    }
                                } else {
                                    mLastTouchDownIndex = childIndex;
                                }
                                mLastTouchDownX = ev.getX();
                                mLastTouchDownY = ev.getY();
                                 //mFirstTouchTarget赋值,就是说child处理了事件
                                newTouchTarget = addTouchTarget(child, idBitsToAssign);
                                alreadyDispatchedToNewTouchTarget = true;
                                break;
                            }

                            ...
                        }
                        if (preorderedList != null) preorderedList.clear();
                    }

                    if (newTouchTarget == null && mFirstTouchTarget != null) {
                        ...
                    }
                }
            }

            // Dispatch to touch targets.
            //所有子View都没处理事件
            if (mFirstTouchTarget == null) {
                // No touch targets so treat this as an ordinary view.
                //那么这里穿的child是null,就是调用super.dispatchTouchEvent(event),就是View.dispatchTouchEvent(event)
                handled = dispatchTransformedTouchEvent(ev, canceled, null,
                        TouchTarget.ALL_POINTER_IDS);
            } else {
                ...
            }

            ...
        }

        ...
        return handled;
    }
private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
            View child, int desiredPointerIdBits) {
        final boolean handled;

        // Canceling motions is a special case.  We don't need to perform any transformations
        // or filtering.  The important part is the action, not the contents.
        final int oldAction = event.getAction();
        if (cancel || oldAction == MotionEvent.ACTION_CANCEL) {
            event.setAction(MotionEvent.ACTION_CANCEL);
            if (child == null) {
                //如果所有子view都没有处理,就调用View本身的分发
                handled = super.dispatchTouchEvent(event);
            } else {
                //分发到子view,同样开始遍历
                handled = child.dispatchTouchEvent(event);
            }
            event.setAction(oldAction);
            return handled;
        }
...

3)view的处理过程:主要是onTouchListener、OnTouchEvent、onClick的关系

public boolean dispatchTouchEvent(MotionEvent event) {
        ...

        boolean result = false;

        ...

        if (onFilterTouchEventForSecurity(event)) {
            if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
                result = true;
            }
            //noinspection SimplifiableIfStatement
            ListenerInfo li = mListenerInfo;
            if (li != null && li.mOnTouchListener != null
                    && (mViewFlags & ENABLED_MASK) == ENABLED
                    && li.mOnTouchListener.onTouch(this, event)) {
                //设置了OnTouchListener且onTouch返回 true,则看下面一行
                result = true;
            }
            //设置了OnTouchListener且onTouch返回 true就不会走onTouchEvent了
            if (!result && onTouchEvent(event)) {
                result = true;
            }
        }

        ...

        return result;
    }
public boolean onTouchEvent(MotionEvent event) {
        final float x = event.getX();
        final float y = event.getY();
        final int viewFlags = mViewFlags;
        final int action = event.getAction();


        final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE
                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;

        if ((viewFlags & ENABLED_MASK) == DISABLED) {
            if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
                setPressed(false);
            }
            mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
            // A disabled view that is clickable still consumes the touch
            // events, it just doesn't respond to them.
            //即使disabled,也是可点击也会消费事件
            return clickable;
        }
        if (mTouchDelegate != null) {
            if (mTouchDelegate.onTouchEvent(event)) {
                return true;
            }
        }

        if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
            switch (action) {
                case MotionEvent.ACTION_UP:
                    ...

                            // Only perform take click actions if we were in the pressed state
                            if (!focusTaken) {
                                // Use a Runnable and post this rather than calling
                                // performClick directly. This lets other visual state
                                // of the view update before click actions start.
                                if (mPerformClick == null) {
                                    mPerformClick = new PerformClick();
                                }
                                if (!post(mPerformClick)) {
                                    //走onClick了
                                    performClickInternal();
                                }
                            }
                        }

                        ...
                    break;

                case MotionEvent.ACTION_DOWN:
                    ...
                    break;
                case MotionEvent.ACTION_MOVE:
                    ...
                    break;
            }

            return true;
        }

        return false;
    }

二、滑动冲突

1、冲突场景

ViewGroup的滑动和子view的滑动有冲突。

外部横向,里面竖向,那就是看外部啥时候拦截。

外部里面都是相同方向,那就要看具体的业务规则了。

2、解决原理

因为ViewGroup的onInterceptTouchEvent默认是不拦截的,所以:

解决滑动冲突的要点重写onInterceptTouchEvent,根据冲突场景的规则来 判断是否拦截,即isIntercept的赋值规则。其他代码不动即可。

(还有个内部拦截法,用子view调用parent.requestDisallowInterceptTouchEvent(true),就不让parent拦截

@Override
    public boolean onInterceptTouchEvent(MotionEvent motionEvent) {
        //解决滑动冲突
        boolean isIntercept = false;

        int x = (int) motionEvent.getX();
        int y = (int) motionEvent.getY();

        switch (motionEvent.getAction()) {
            case MotionEvent.ACTION_DOWN:
                //down不能拦截,因为已拦截就都给你了。
                mLastXIntercept = x;
                mLastYIntercept = y;
                break;
            case MotionEvent.ACTION_MOVE:

                //是横向的滑动
                boolean isHorizontal = Math.abs(x - mLastXIntercept) > Math.abs(y - mLastYIntercept);

                //解决滑动冲突的要点:根据冲突场景的规则来 判断是否拦截,即isHorizontal如果取值
                if (isHorizontal) {
                    //此处一旦拦截,后面的ACTION就不会在调用onInterceptTouchEvent
                    isIntercept = true;
                }
                break;
            case MotionEvent.ACTION_UP:
                //up不能拦截,因为拦截了没啥意义。因为如果前面拦截了Down,那自然Up也会给到。
                //另外,如果只拦截了UP,那子view即使处理了其他事件,那也不会走onClick。
                break;
        }

        Log.i(TAG, "onInterceptTouchEvent: isIntercept:" + isIntercept);

        //此处要记录下 拦截时的 开始的 触摸点(仅用于下面onTouchEvent处理滑动使用)
        mLastX = mLastXIntercept;
        mLastY = mLastYIntercept;

        mLastXIntercept = x;
        mLastYIntercept = y;

        return isIntercept;
    }

本文分享自微信公众号 - 胡飞洋(hfydwxgzh),作者:胡飞洋

原文出处及转载信息见文内详细说明,如有侵权,请联系 yunjia_community@tencent.com 删除。

原始发表时间:2020-03-03

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • 这次,我把Android事件分发机制翻了个遍

    作者:积木zz 链接:https://juejin.im/post/5eb3e0d6f265da7c002028cd 以下是原文:

    胡飞洋
  • View的滑动方式 详细介绍

    用于追踪手指滑动速度的。例如相册的图片,手指快速左右滑动会切换图片,慢则不会切换。获取速度前,要先调用computeCurrentVelocity计算速度,如下...

    胡飞洋
  • 必要掌握!Window、WindowManager !

    Window是View的管理者,当我们说创建Window时,一方面指实例化这个管理者,一方面指 用WindowManager.addView()添加view,以...

    胡飞洋
  • 这次,我把Android事件分发机制翻了个遍

    作者:积木zz 链接:https://juejin.im/post/5eb3e0d6f265da7c002028cd 以下是原文:

    胡飞洋
  • 微信小程序--基于ColorUI构建皮皮虾短视频去水印组件(仅供学习使用)

    没错,我是皮友,我想学习舞蹈(/doge)和瑜伽 ,要无水印的那种有助于我加深学习。

    Kindear
  • 前端-微信小程序开发(3):这是一个组件

    之前这个组件是一个容器类组件,弹出层可设置载入的html结构,然后再设置各种事件即可,这种组件有一个特点:

    grain先森
  • 小程序快速入门教程 1.2 WXML 和 WXSS

    这节开始学习小程序的视图层,WXML 和 WXSS 就像网页开发的 HTML 和 CSS,一个负责页面结构,一个负责页面样式,即美化页面。

    twowinter
  • uniapp图片弹框效果

    需求:点击提交按钮,提交成功后会弹出一个弹框,提示成功,点击右上角的叉号或者我知道了,隐藏弹框效果。

    王小婷
  • 16.普通用户、网格长、网格员,操作数据(3)newapp/components/putong.vue

    玩蛇的胖纸
  • addSubView需要注意的几个点为什么要在addsubview:一个view对象后,release它?

    addSubview: Adds a view to the end of the receiver’s list of subviews. 译:增加一个视图到...

    猿人谷

扫码关注云+社区

领取腾讯云代金券