最强事件分发源码解读

首先理解事件分发后的事件要被干什么

答案是最后我们的事件是要被消费掉,那么消费又是被谁来消费掉得了,这里就不卖关子了,没错是被view消费掉了,这个时候就会有疑问了view咋消费的,这就涉及到View和ViewGroup,下面我们就对他俩来详细解读

view消费事件两个重要方法

dispatchTouchEvent()和onTouchEvent()方法

1. dispatchTouchEvent()看源码,上代码

···其他代码···
ListenerInfo li = mListenerInfo;
            if (li != null && li.mOnTouchListener != null
                    && (mViewFlags & ENABLED_MASK) == ENABLED
//这句判断看到没,执行ontouch方法,如果返回true很明显result是true,后面的if判断
//的onTouchEvent不会执行,他不执行我们若是在某个点击事件设置了点击
//和设置onTouch并且ontouch返回true,onclick不会执行。这里只说结果,原因稍后再
//说onTouchEvent的方法里面解释
                    && li.mOnTouchListener.onTouch(this, event)) {
                result = true;
            }
//如果result为false执行onTouchEvent,仅针对click事件来说这里,click事件会
//在action_up后执行,稍后解读这个代码
            if (!result && onTouchEvent(event)) {
                result = true;
            }
···其他代码···

总结上面的代码:

一个view,这里就用button来说。我们设置
textTv.setOnClickListener { }
textTv.setOnTouchListener { v, event -> true }若true这onclick不执行只执行ontouch,若false,则ontouch执行而onclick执行与否不知道。老兄们上面代码只能得出这个结论,但我们打印log可以看到为false是onclick会执行并且在我们抬手之后执行,是不是很神奇,来上代码

2.onTouchEvent()源码

case MotionEvent.ACTION_UP:
···其他代码···
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)) {
//看这里,这个是不是很熟悉,我们做模拟点击的时候performClick(),这个方法就是会
//调用performClick兄弟~~~~
                                    performClickInternal();
                                }
                            }
···其他代码···
 private boolean performClickInternal() {
        // Must notify autofill manager before performing the click actions to avoid scenarios where
        // the app has a click listener that changes the state of views the autofill service might
        // be interested on.
        notifyAutofillManagerOnClick();

        return performClick();
    }

 public boolean performClick() {
        // We still need to call this method to handle the cases where performClick() was called
        // externally, instead of through performClickInternal()
        notifyAutofillManagerOnClick();

        final boolean result;
        final ListenerInfo li = mListenerInfo;
//看这个重要的if语句,是不是很了然,咱们自己写监听回调也差不多这样写咯
        if (li != null && li.mOnClickListener != null) {
            playSoundEffect(SoundEffectConstants.CLICK);
            li.mOnClickListener.onClick(this);
            result = true;
        } else {
            result = false;
        }

        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);

        notifyEnterOrExitForAutoFillIfNeeded(true);

        return result;
    }

总结View消费事件通过touch和click:

我们事件最终是由view来消费的,在view中有dispatchTouchEvent()和onTouchEvent()方法来下消费事件的,对于click事件,我们首先是触发了ontouch,当我们重写ontouch事件返回值决定click是否执行,返回值true那么click不执行,返回值false则click和ontouch都执行,而click是在手抬起执行的。

注意这里ontouch()的返回值为true是要是也想执行click,可以调用performClick()

textTv.setOnTouchListener { v, event ->
            textTv.performClick()
            true }
    }

知道了事件消费,下面我们的重头戏来了

事件分发ViewGroup,ViewGroup的方法

dispatchTouchEvent(),onInterceptTouchEvent()
在事件分发dispatchTouchEvent中有几个很重要的变量intercepted,disallowIntercept,mFirstTouchTarget,MotionEvent.ACTION_DOWN,cancelChild等先记着等会介绍

先说一下dispatchTouchEvent分发的大概过程

首先我们我们说三个action,ACTION_DOWN、ACTION_MOVE(分发会执行多次,后面会有介绍)、ACTION_CANCEL(move拦截时会看到他的使用)

1.dispatchTouchEvent事件分发的down事件执行流程

image.png

这个图是不是有点伤眼睛,太小了,这时我笑了,大东一笑代码来到,淦他上代码

 public boolean dispatchTouchEvent(MotionEvent ev) {
     ··其他代码···
            final boolean intercepted;
            //1.down事件分发处理先询问自己是否拦截
            //2.mFirstTouchTarget处理他不为空时询问自己是否拦截,move事件会使用
            if (actionMasked == MotionEvent.ACTION_DOWN
                    || mFirstTouchTarget != null) {
                //不允许拦截
                final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
                if (!disallowIntercept) {
                    //如果拦截就onInterceptTouchEvent返回true,不拦截返回false
                    intercepted = onInterceptTouchEvent(ev);
                    ev.setAction(action); // restore action in case it was changed
                } else {
                    intercepted = false;
                }
            } else {
                intercepted = true;
            }

        ···其他代码···
            //intercepted是false说明不拦截,向下分发执行下面代码,
            //intercepted是true说明拦截,不分发,执行if外面的代码,
            if (!canceled && !intercepted) {
                View childWithAccessibilityFocus = ev.isTargetAccessibilityFocus()
                        ? findChildWithAccessibilityFocus() : null;

                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;
                    removePointersFromTouchTargets(idBitsToAssign);
                    final int childrenCount = mChildrenCount;
                    if (newTouchTarget == null && childrenCount != 0) {
                        final float x =
                                isMouseEvent ? ev.getXCursorPosition() : ev.getX(actionIndex);
                        final float y =
                                isMouseEvent ? ev.getYCursorPosition() : ev.getY(actionIndex);
                        //将所有的子view排序,里面的代码不看了知道就行了
                        final ArrayList preorderedList = buildTouchDispatchChildList();
                        final boolean customOrder = preorderedList == null
                                && isChildrenDrawingOrderEnabled();
                        final View[] children = mChildren;
                        //遍历所有的view可能也是viewgroup,总之就是孩子
                        for (int i = childrenCount - 1; i >= 0; i--) {
                            final int childIndex = getAndVerifyPreorderedIndex(
                                    childrenCount, i, customOrder);
                            final View child = getAndVerifyPreorderedView(
                                    preorderedList, children, childIndex);
                            //可以收到对应的事件
                            if (!child.canReceivePointerEvents()
                                    || !isTransformedTouchPointInView(x, y, child, null)) {
                                continue;
                            }
···其他代码···
                            //分发事件给孩子这时child不为空,内部代码递归调用分发事件
                            //是这个dispatchTransformedTouchEvent方法
                            if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
                                mLastTouchDownTime = ev.getDownTime();
                                if (preorderedList != null) {
                                    for (int j = 0; j < childrenCount; j++) {
                                        if (children[childIndex] == mChildren[j]) {
                                            mLastTouchDownIndex = j;
                                            break;
                                        }
                                    }
                                } else {
                                    mLastTouchDownIndex = childIndex;
                                }
                                mLastTouchDownX = ev.getX();
                                mLastTouchDownY = ev.getY();
                                newTouchTarget = addTouchTarget(child, idBitsToAssign);
                                alreadyDispatchedToNewTouchTarget = true;
                                break;
                            }
                            ev.setTargetAccessibilityFocus(false);
                        }
                        if (preorderedList != null) preorderedList.clear();
                    }
                    if (newTouchTarget == null && mFirstTouchTarget != null) {
                        newTouchTarget = mFirstTouchTarget;
                        while (newTouchTarget.next != null) {
                            newTouchTarget = newTouchTarget.next;
                        }
                        newTouchTarget.pointerIdBits |= idBitsToAssign;
                    }
                }
            }
            //这里有拦截事件有关,mFirstTouchTarget为空的情况两种
            //1.down事件时,拦截2.move事件时拦截,但是是后面执行move事件时置为的空
            //dispatchTransformedTouchEvent消费掉事件
            if (mFirstTouchTarget == null) {
                handled = dispatchTransformedTouchEvent(ev, canceled, null,
                        TouchTarget.ALL_POINTER_IDS);
            } else {//mFirstTouchTarget不为空,move事件第一次执行就会走这里
                TouchTarget predecessor = null;
                TouchTarget target = mFirstTouchTarget;
                while (target != null) {
                    final TouchTarget next = target.next;
                    if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
                        handled = true;
                    } else {
                        //如果move时拦截就说明intercepted为true,那么cancelChild就是true
                        final boolean cancelChild = resetCancelNextUpFlag(target.child)
                                || intercepted;
                        //这时dispatchTransformedTouchEvent的第二各参数为true,内部实现
                        //逻辑就是保存当前move事件的event,然后设置action的event为cancel
                        //这个时候target.child不为空接着递归调用分发事件,下面if (cancelChild) 
                        //里面逻辑将mFirstTouchTarget置为空
                        if (dispatchTransformedTouchEvent(ev, cancelChild,
                                target.child, target.pointerIdBits)) {
                            handled = true;
                        }
                        //里面逻辑将mFirstTouchTarget置为空,后面执行move事件就会拦截了
                        //事件
                        if (cancelChild) {
                            if (predecessor == null) {
                                mFirstTouchTarget = next;
                            } else {
                                predecessor.next = next;
                            }
                            target.recycle();
                            target = next;
                            continue;
                        }
                    }
                    predecessor = target;
                    target = next;
                }
            }
···其他代码···
        return handled;
    }

这里在贴出dispatchTransformedTouchEvent处理事件的方法代码

private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
            View child, int desiredPointerIdBits) {
···其他代码···
        final boolean handled;
        //这里是对第二个参数true和false的处理,其实就是move事件的拦截第一次move
        //处理逻辑
        final int oldAction = event.getAction();
        if (cancel || oldAction == MotionEvent.ACTION_CANCEL) {
            event.setAction(MotionEvent.ACTION_CANCEL);
            if (child == null) {//第一次进入child不是空所以还是递归调用分发事件走else
                handled = super.dispatchTouchEvent(event);
            } else {
                handled = child.dispatchTouchEvent(event);
            }
            //重新设置为move事件,所以说move是多次执行
            event.setAction(oldAction);
            return handled;
        }
···其他代码···
        //这里是down事件的拦截和move事件拦截第二次进入的逻辑,child是空view消费事件
        if (child == null) {
            handled = super.dispatchTouchEvent(transformedEvent);
        } else {//child不是空,递归调用向下分发的方法
            final float offsetX = mScrollX - child.mLeft;
            final float offsetY = mScrollY - child.mTop;
            transformedEvent.offsetLocation(offsetX, offsetY);
            if (! child.hasIdentityMatrix()) {
                transformedEvent.transform(child.getInverseMatrix());
            }
            //递归调用向下分发的方法
            handled = child.dispatchTouchEvent(transformedEvent);
        }
···其他代码···
        return handled;
    }

以上两个方法的注释把整个逻辑写出来了很好理解,下面在总结一波

总结:

事件分发需要从down和move两个事件来分析。
1. 首先是down,在进入dispatchTouchEvent方法后会先询问自己要不要拦截intercepted = onInterceptTouchEvent(ev);若是intercepted得到onInterceptTouchEvent方法的返回值是true拦截,会执行if (mFirstTouchTarget == null)里面的逻辑调用dispatchTransformedTouchEvent处理事件的方法,第三个参数child为空,调用view的消费事件自己消费了。若是intercepted得到onInterceptTouchEvent方法的返回值是false不拦截,会执行if (!canceled && !intercepted)里面的逻辑,这里面先是讲所用的child排序final ArrayList preorderedList = buildTouchDispatchChildList()然后再遍历每一个child执行if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign))处理事件的方法,这里child因为不为空就会在内部递归调用分发方法直到child是view时消费事件。

  1. 然后是move,move在down后执行,是viewgroup第二次自己消费事件的机会。同样的还是询问自己是否拦截intercepted = onInterceptTouchEvent(ev)。若拦截,则执行
if (mFirstTouchTarget == null) {
                // No touch targets so treat this as an ordinary view.
                handled = dispatchTransformedTouchEvent(ev, canceled, null,
                        TouchTarget.ALL_POINTER_IDS);
            } else {

里面的else逻辑,因为mFirstTouchTarget不为空了,这里面有变量final boolean cancelChild = resetCancelNextUpFlag(target.child) || intercepted;因为intercepted为true所以cancelChild为true。然后执行

if (dispatchTransformedTouchEvent(ev, cancelChild,
                                target.child, target.pointerIdBits))因为cancelChild为true执行if (cancel || oldAction == MotionEvent.ACTION_CANCEL)

里面的逻辑,因为child不为空会再次递归调用分发事件,然而

if (cancelChild) {
                            if (predecessor == null) {
                                mFirstTouchTarget = next;
                            } else {
                                predecessor.next = next;
                            }

将mFirstTouchTarget赋值空就走了和当初down事件拦截的逻辑。若是不拦截就向下分发不做多余的介绍了

到了这里我们来说一说事件冲突

冲突一直存在,只是有些google工程师给我们解决了,有些没有,当我们遇到了就要通过上面的总结去解决。这里要在介绍一个变量disallowIntercept这是不允许拦截的变量我可以通过getParent().requestDisallowInterceptTouchEvent(true);传入true或false来控制是否拦截。一般拦截分为内部拦截和外部拦截,具体遇到了具体处理。

如果觉得可以给大东个赞

你可能感兴趣的:(最强事件分发源码解读)