android SDK-25事件分发机制--源码正确解析

android SDK-25事件分发机制–源码正确解析

Android 事件分发分为View和ViewGroup的事件分发,ViewGroup比View过一个拦截判断,viewgroup可以拦截事件,从而决定要不要把事件传递给子view,因为view没有子view所以不存在拦截事件的情况。

事件分发主要从事件的分发,拦截,和处理三个函数的调用逻辑关系来分析。

public boolean dispatchTouchEvent(MotionEvent event) {

}

public boolean onInterceptTouchEvent(MotionEvent ev) {

}

public boolean onTouchEvent(MotionEvent event) {

}

首先,屏幕上面一个点击事件,通过传感器捕获到点击,然后知道把点击事件传递到activity 到PhoneWindow,再到,DecorView 最后就到我们自己在布局文件中的view或者viewgroup。

下面分析dispatchTouchEvent源码 :(sdk-25)(==>这个标记为重点,不用全懂,只要把==>这个标记处的逻辑理清楚就行)

 @Override
public boolean dispatchTouchEvent(MotionEvent ev) {

    //检验是不是利用辅助功能点击事件,根本不用管 
    if (mInputEventConsistencyVerifier != null) {
        mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
    }

    // If the event targets the accessibility focused view and this is it, start
    // normal event dispatch. Maybe a descendant is what will handle the click.
    if (ev.isTargetAccessibilityFocus() && isAccessibilityFocusedViewOrHost()) {
        ev.setTargetAccessibilityFocus(false);
    }
    //辅助功能点击事件的判断和处理根本不用管,直接不要管,跳转到下一个重点

    // ==> 一个标志,初始值为不处理,意识就是不处理MotionEvent
    boolean handled = false;
    if (onFilterTouchEventForSecurity(ev)) {
        final int action = ev.getAction();
        final int actionMasked = action & MotionEvent.ACTION_MASK;

        // Handle an initial down.
        // ==> 处理第一个点击事件(事件分为,点击事件,move事件,up事件,所以点击事件是第一个事件)
        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;
        // ==> 判断要不要打断,如果不是点击事件,并且mFirstTouchTarget为null,则该viewgroup则打断拦截事件。
        if (actionMasked == MotionEvent.ACTION_DOWN
                || mFirstTouchTarget != null) {
            final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
            if (!disallowIntercept) {
                intercepted = onInterceptTouchEvent(ev);
                ev.setAction(action); // restore action in case it was changed
            } else {
                intercepted = false;
            }
        } else {
            // There are no touch targets and this action is not an initial down
            // so this view group continues to intercept touches.
            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 the event is targeting accessiiblity focus we give it to the
            // view that has accessibility focus and if it does not handle it
            // we clear the flag and dispatch the event to all children as usual.
            // We are looking up the accessibility focused host to avoid keeping
            // state since these events are very rare.
            View childWithAccessibilityFocus = ev.isTargetAccessibilityFocus()
                    ? findChildWithAccessibilityFocus() : null;
            // ==>如果是down事件,进行遍历子view,并且把事件分发给子view,前提是down事件的坐
            标必须在子view中等等条件
            ==>这句话,请把下面的源码分析完再一定回来看一看,你要思考一下,这里如果是down事件才
            会进去,如果是move事件那么不会进去分发了,其实往后看源码会发现,在down事件分发给
            一个child,如果这个child消费了这个down事件,那么这个child就会被保存起来,以后的
            move(可能0到多次move),up都会直接分发给这个child,就不用每次再去遍历所有的Child
            这些效率就提高和很多,但是你也会想到,如果一个down事件被某个child消费只有,其它
            child就无法被分发事件了,除非我们手动调用child的分发方法,或者打断事件序列,从发分发一个down事件,这段话请看完后面的源码再来推敲一下,就完全理解事件分发机制了。
            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;
                    for (int i = childrenCount - 1; i >= 0; i--) {
                        final int childIndex = getAndVerifyPreorderedIndex(
                                childrenCount, i, customOrder);
                        final View child = getAndVerifyPreorderedView(
                                preorderedList, children, childIndex);

                        // If there is a view that has accessibility focus we want it
                        // to get the event first and if not handled we will perform a
                        // normal dispatch. We may do a double iteration but this is
                        // safer given the timeframe.
                        if (childWithAccessibilityFocus != null) {
                            if (childWithAccessibilityFocus != child) {
                                continue;
                            }
                            childWithAccessibilityFocus = null;
                            i = childrenCount - 1;
                        }
                    // ==>判断这个子view能否接受点击事件和子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进行处理了,马上进入这个方法看看吧
                        if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) 

// ==>dispatchTransformedTouchEvent方法

 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) {
            handled = super.dispatchTouchEvent(event);
        } else {
            handled = child.dispatchTouchEvent(event);
        }
        event.setAction(oldAction);
        return handled;
    }

    // Calculate the number of pointers to deliver.
    final int oldPointerIdBits = event.getPointerIdBits();
    final int newPointerIdBits = oldPointerIdBits & desiredPointerIdBits;

    // If for some reason we ended up in an inconsistent state where it looks like we
    // might produce a motion event with no pointers in it, then drop the event.
    if (newPointerIdBits == 0) {
        return false;
    }

    // If the number of pointers is the same and we don't need to perform any fancy
    // irreversible transformations, then we can reuse the motion event for this
    // dispatch as long as we are careful to revert any changes we make.
    // Otherwise we need to make a copy.
    final MotionEvent transformedEvent;
    if (newPointerIdBits == oldPointerIdBits) {
        if (child == null || child.hasIdentityMatrix()) {

            if (child == null) {
                handled = super.dispatchTouchEvent(event);
            } else {

                final float offsetX = mScrollX - child.mLeft;
                final float offsetY = mScrollY - child.mTop;
                event.offsetLocation(offsetX, offsetY);

                handled = child.dispatchTouchEvent(event);

                event.offsetLocation(-offsetX, -offsetY);
            }
            return handled;
        }
        transformedEvent = MotionEvent.obtain(event);
    } else {
        transformedEvent = event.split(newPointerIdBits);
    }

    // Perform any necessary transformations and dispatch.
    if (child == null) {
    // ==>如果child为空,直接调用该viewgroup自己父类的dispatchTouchEvent,也就是viewdispatchTouchEvent方法,点击进去会发现它会调用onTouchEvent,也就是说如果viewGroup如果没有child那么他就会调用自己的onTouchEvent方法来消费这个事件,这个handle就表明了这个事件viewgroup自己是否消费
        handled = super.dispatchTouchEvent(transformedEvent);
    } else {
        final float offsetX = mScrollX - child.mLeft;
        final float offsetY = mScrollY - child.mTop;
        transformedEvent.offsetLocation(offsetX, offsetY);
        if (! child.hasIdentityMatrix()) {
            transformedEvent.transform(child.getInverseMatrix());
        }
        // ==>我们的child不为空的时候,就调用child事件分发方法,于是到这里可以看到事件的传递了,先来分析简单的情况,如果child是view不是viewgroup,那么dispatchTouchEvent流程就简单了,会调用onTouchEvent来告诉父view,child它是否消费父亲分发给他的事件,这个handle就表明了这个事件clild是否消费
        handled = child.dispatchTouchEvent(transformedEvent);

    }

    // Done.
    transformedEvent.recycle();
    return handled;
}

//这个重要的方法分析完之后,马上返回刚才源码的地方,继续。。。

//如果刚才,我们的child不为空并且child消费down事件,那么就很棒了,说明有child处理事件了

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();
            // ==>重点,从上面的if条件可以看出,有child消费down事件才会执行到这里,这个方法点
        进去发现mFirstTouchTarget = target;     
        这句代码,很重要哦。很明显就是把消费down事件的child赋值给mFirstTouchTarget,从而保存起来
                            newTouchTarget = addTouchTarget(child, idBitsToAssign);
            // ==> alreadyDispatchedToNewTouchTarget = true; 已经把事件分发给新的触摸目标
                下面在分发的时候会用到
                            alreadyDispatchedToNewTouchTarget = true;
                            break;
                        }

                        // The accessibility focus didn't handle the event, so clear
                        // the flag and do a normal dispatch to all children.
                        ev.setTargetAccessibilityFocus(false);
                    }
                    if (preorderedList != null) preorderedList.clear();
                }
            //这里,如果是down事件,并且mFirstTouchTarget != null则加入链表newTouchTarget,这里不要管
                if (newTouchTarget == null && mFirstTouchTarget != null) {
                    // Did not find a child to receive the event.
                    // Assign the pointer to the least recently added target.
                    newTouchTarget = mFirstTouchTarget;
                    while (newTouchTarget.next != null) {
                        newTouchTarget = newTouchTarget.next;
                    }
                    newTouchTarget.pointerIdBits |= idBitsToAssign;
                }
            }
        }
        // ==> 由于刚才mFirstTouchTarget被赋值为消息了down事件的child,所以不为空了
        // Dispatch to touch targets.
        if (mFirstTouchTarget == null) {
        // 这里非常重要,如果child为空,表明viewgroup在分发事件给child的dispatchTouchEvent被返回了false,说明子view都不消费down事件,那么这里会调用dispatchTransformedTouchEvent这个重要的方法,点进去就会发现,当child为null的时候,会调用viewgroup自己的父类View的dispatchTouchEvent,从而调用onTouchEvent,就是说儿子不消费,给老子再看看要不要消费。
            // No touch targets so treat this as an ordinary view.
            handled = dispatchTransformedTouchEvent(ev, canceled, null,
                    TouchTarget.ALL_POINTER_IDS);
        } else {
            // Dispatch to touch targets, excluding the new touch target if we already
            // dispatched to it.  Cancel touch targets if necessary.
            TouchTarget predecessor = null;
            TouchTarget target = mFirstTouchTarget;
            while (target != null) {
                final TouchTarget next = target.next;
                if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
                    handled = true;
                } else {
                    final boolean cancelChild = resetCancelNextUpFlag(target.child)
                            || intercepted;
        // ==>看到这里,你是不是发现怎么又调用了这个重要的,吧事件分发给child的方法,刚才不是已
            经分发了,这不是第二次又来分发吗?,当然不会,你看前面的,第一次分发事件的时候已经讲
            alreadyDispatchedToNewTouchTarget=true;了
                    if (dispatchTransformedTouchEvent(ev, cancelChild,
                            target.child, target.pointerIdBits)) {
                        handled = true;
                    }
                    if (cancelChild) {
                        if (predecessor == null) {
                            mFirstTouchTarget = next;
                        } else {
                            predecessor.next = next;
                        }
                        target.recycle();
                        target = next;
                        continue;
                    }
                }
                predecessor = target;
                target = next;
            }
        }

        // Update list of touch targets for pointer up or cancel, if needed.
        if (canceled
                || actionMasked == MotionEvent.ACTION_UP
                || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
            resetTouchState();
        } else if (split && actionMasked == MotionEvent.ACTION_POINTER_UP) {
            final int actionIndex = ev.getActionIndex();
            final int idBitsToRemove = 1 << ev.getPointerId(actionIndex);
            removePointersFromTouchTargets(idBitsToRemove);
        }
    }

    if (!handled && mInputEventConsistencyVerifier != null) {
        mInputEventConsistencyVerifier.onUnhandledEvent(ev, 1);
    }
    return handled;
}

这里写图片描述
总结:事件分发,viewgroup自己先判断要不要拦截事件,和有没有调用过requestDisallowInterceptTouchEvent方法来不拦截事件,如果不拦截,当down事件的时候,遍历child,看child是否消费,child如果消息,则被保存下来,后面的事件就不遍历直接分发给他,如果child不消费,那么viewgruop继续执行,调用自己onTouchEvent方法来判断自己是不是要消费事件。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值