Android事件分发(3)--ViewGroup源码分析

一、ViewGroup的onInterceptTouchEvent源码分析

onInterceptTouchEvent比较简单先看他的源码

    public boolean onInterceptTouchEvent(MotionEvent ev) {
    //1、判断是否是鼠标设备操作
    //2、ACTION_DOWN事件
    //3、是否是首要按钮按下,如鼠标左键
    //4、是否是滑动条     
    //看意思以上是兼容安卓非手机设备用的判断,满足的话,就返回true,拦截事件分发
        if (ev.isFromSource(InputDevice.SOURCE_MOUSE)
                && ev.getAction() == MotionEvent.ACTION_DOWN
                && ev.isButtonPressed(MotionEvent.BUTTON_PRIMARY)
                && isOnScrollbarThumb(ev.getX(), ev.getY())) {
            return true;
        }
        //默认返回false不拦截事件分发
        return false;
    }

onInterceptTouchEvent 作用就是要不要拦截向子View分发事件,如果想拦截的话,需要重写onInterceptTouchEvent。

二、ViewGroup的dispatchTouchEvent源码分析

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
    //如果输入一致性检查事件不为null,先执行输入前后一致性检查
    //源码英文注释说是为了debug的目的,估计是设置断点后,再次运行的时候,为了不丢失事件,检查是否是同一个输入,可忽略
        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.
        //如果事件对象是容易获取焦点的view,开始普通事件分发,可能是某个后代会处理点击。
        //貌似是用来判断 motion event是否设置了容易获取焦点Flags
        //这个flags是FLAG是_WINDOW_IS_OBSCURED,源码意思大约是设置事件对象,是否部分或者全部被遮挡到了
        if (ev.isTargetAccessibilityFocus() && isAccessibilityFocusedViewOrHost()) {
            ev.setTargetAccessibilityFocus(false);
        }

        //handled 是最终要返回的结果值
        boolean handled = false;
        //onFilterTouchEventForSecurity 对事件进行安全检查,如果true可执行,false就放弃
        //onFilterTouchEventForSecurity 里面进行了是否要遮挡进行过滤,以及event的对象是否被遮挡的两个判断
        if (onFilterTouchEventForSecurity(ev)) {
        //未被遮挡进入了此if内部
            final int action = ev.getAction();
            final int actionMasked = action & MotionEvent.ACTION_MASK;

            // Handle an initial down.
            //处理最初的ACTION_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.
                //当开始了一个新的手势,抛弃了之前所有的状态
                //由于app切换,ANR或者其他状态改变,框架可能已经放弃了对前一个手势的Up 和cancel的处理
                //cancelAndClearTouchTargets 清空了之前所有的找到的触摸对象,里面调用了dispatchTransformedTouchEvent(event, true, target.child, target.pointerIdBits);对子View的事件进行了取消,传递的第二个参数true 是是否取消的标志
                //里面调用了clearTouchTargets 对比较重要的mFirstTouchTarget对象赋值null
               //mFirstTouchTarget的英文注释 First touch target in the linked list of touch targets.是第一个找到的触摸对象
                cancelAndClearTouchTargets(ev);
                resetTouchState();
            }
            //检查是否拦截
            // Check for interception.
            final boolean intercepted;
            //第一种情况ACTION_DOWN的时候判断拦截,
            //第二种情况,已经找到了要处理事件的字View或者子ViewGroup
            if (actionMasked == MotionEvent.ACTION_DOWN
                    || mFirstTouchTarget != null) {
                    //之后又对disallowIntercept进行了判断,disallowIntercept的意思是,是否禁用拦截,disallowIntercept可以使用requestDisallowInterceptTouchEvent方法自己进行设置,后面会具体分析
                final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
                if (!disallowIntercept) {
                //没有禁用拦截,就会根据拦截函数onInterceptTouchEvent的返回值,进行拦截判断,是否拦截
                    intercepted = onInterceptTouchEvent(ev);
                    ev.setAction(action); // restore action in case it was changed恢复action,防止action被改变了
                } 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.
                //没有找到处理MotionEvent的目标对象,而且也不是最初的ACTION_DOWN,也就是现在是up 或者move事件了
                //mFirstTouchTarget 为null说明自己没有需要处理事件的对象,也就是自己这个ViewGroup下没有View要处理事件,所以拦截
                //
                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;

//ACTION_POINTER_DOWN 是说在有一个触摸点的情况下,又有手指触摸屏幕。多点触控的判断
//主要关心ACTION_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);
//有效的子View的数量
                    final int childrenCount = mChildrenCount;
                    //newTouchTarget 为null且子view数量不为0
                    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.
                        //找到一个能接收事件的子View,视图层次上从上层到下层的顺序查找
                        final ArrayList<View> preorderedList = buildTouchDispatchChildList();
                        final boolean customOrder = preorderedList == null
                                && isChildrenDrawingOrderEnabled();
                        final View[] children = mChildren;
                        //是子View倒序遍历子View,因为在添加子view到group的过程中,先添加的显示在底层,后添加的显示在上层,所以查找的时候,先从可见的上层查找起
                        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;
                            }
//子View满足可触摸和在触摸范围内
//找到某一指定的子view的TouchTarget对象,传递参数有子View,返回子VIew的TouchTarget对象
                            newTouchTarget = getTouchTarget(child);
                            //没有找到子View的TouchTarget对象的处理
                            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);
                            //把经过一定改变的MotionEvent传递给子View的相对应的区域,是在这个方法里,进行的子View的分发事件的调用。稍后单独分析。
                            if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
                                // Child wants to receive touch within its bounds.
                                //返回true表示子View想处理消费事件,
                                mLastTouchDownTime = ev.getDownTime();
                                //找到消费事件的view的index
                                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();
                                //把要消费事件的子View的TouchTarget对象放到list开头
                                //addTouchTarget 里面对mFirstTouchTarget进行了赋值,并返回,mFirstTouchTarget和newTouchTarget 此时指向相同
                                newTouchTarget = addTouchTarget(child, idBitsToAssign);
         //已经分发标识设置为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();
                    }
//没有找到消费事件的子View
                    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;
                    }
                }
            }
//以上是对 不拦截,未取消事件的处理和分发  ,如果找到了要消费事件的view, 那么mFirstTouchTarget 就不应该为空了

//mFirstTouchTarget 为null 一是可能事件都被拦截了,二是没有找到要消费事件的子View
            // Dispatch to touch targets.
            if (mFirstTouchTarget == null) {
                // No touch targets so treat this as an ordinary view.
                //没有触摸对象,把它当成原始的view来处理
                //第三个参数传递是null,在里面判断了null会调用view的dispatchTouchEvent方法,也就是把ViewGroup当成view处理
                handled = dispatchTransformedTouchEvent(ev, canceled, null,
                        TouchTarget.ALL_POINTER_IDS);
            } else {
            //有子View消费事件
            //
                // 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;
                    //alreadyDispatchedToNewTouchTarget为true是在找到newTouchTarget的时候设置的
                    //且alreadyDispatchedToNewTouchTarget设置为true是在ACTION_DOWN的if判断里面的,它消费了ACTION_DOWN事件
                    //所以返回handled = true表示已经有子view消费事件了
                    if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
                        handled = true;
                    } else {
                    // 对于非ACTION_DOWN事件,则继续传递给目标子组件进行处理(注意这里的非ACTION_DOWN事件已经不需要再判断是否拦截)
                        final boolean cancelChild = resetCancelNextUpFlag(target.child)
                                || intercepted;
                        if (dispatchTransformedTouchEvent(ev, cancelChild,
                                target.child, target.pointerIdBits)) {
                                // 如果target子组件进行处理,符合某些条件的话,会传递ACTION_CANCEL给target子组件
                    // 条件是:如果ACTION_DOWN时没有被拦截,而后面的touch事件被拦截,则需要发送ACTION_CANCEL给target子组件
                            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.
            //ACTION_CANCEL或者ACTION_UP,重置touch 的状态
            //mFirstTouchTarget重置为null
            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;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值