Android源码分析之Touch事件分发机制

研究了View的绘制流程,接下来不得不研究下View的Touch事件机制,只有掌握了这两方面的知识,才能对View有全面的认识,Touch事件的入口在Activity中,代码如下:

public boolean dispatchTouchEvent(MotionEvent ev) {
    if (ev.getAction() == MotionEvent.ACTION_DOWN) {
        onUserInteraction();
    }
    if (getWindow().superDispatchTouchEvent(ev)) {
        return true;
    }
    return onTouchEvent(ev);
}

我们可以看到,它首先是由Window来处理的,如果Window不处理,就会交给Activity#onTouchEvent来完成,那么什么情况下会交给Activity来处理呢?我们看下这个方法,代码如下:

/**
* Called when a touch screen event was not handled by any of the views
* under it.  This is most useful to process touch events that happen
* outside of your window bounds, where there is no view to receive it.
*
* @param event The touch screen event being processed.
*
* @return Return true if you have consumed the event, false if you haven't.
* The default implementation always returns false.
*/
public boolean onTouchEvent(MotionEvent event) {
    if (mWindow.shouldCloseOnTouch(this, event)) {
        finish();
        return true;
    }

    return false;
}

注释里说明了,这种情况是点击的区域不在Window的范围内,并且会判断是否需要关闭Activity。

接下来继续看Window是如何处理Touch事件的,这里的Window是PhoneWindow,代码如下:

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

Touch事件最终交给了DecorView来完成,而DecorView又交给了父类ViewGroup来完成,所以真正的入口在ViewGroup中,代码如下:

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.
        // 丢弃之前无用的TouchEvent
        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事件,或者有目标Target,是否拦截通过onInterceptTouchEvent判断
        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;

            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 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);

                        ...
                        // 判断当前的child在不在之前接收事件的view列表里
                        newTouchTarget = getTouchTarget(child);
                        // 找到了接收事件的view,这里将跳出for循环
                        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;
                        }

                        // 这里就是说当前的child不在之前的列表里
                        resetCancelNextUpFlag(child);
                        // 如果这个child要拦截事件,才会走下边的if
                        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();
                            // 把这个view添加到之前的列表中
                            newTouchTarget = addTouchTarget(child, idBitsToAssign);
                            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,那就让最后添加进列表的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;
                }
            }
        }

        // Dispatch to touch targets.
        if (mFirstTouchTarget == null) {
            // TouchTarget这个链表是空的,也就是没有child处理
            // No touch targets so treat this as an ordinary view.
            handled = dispatchTransformedTouchEvent(ev, canceled, null,
                    TouchTarget.ALL_POINTER_IDS);
        } else {
            // 对所有的在TouchTarget链表中的child 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;
                if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
                    // 如果已经由一个原先不在链表中的子view处理,就是handled完成了
                    handled = true;
                } else {
                    循环查找能够dispatch的view
                    final boolean cancelChild = resetCancelNextUpFlag(target.child)
                            || intercepted;
                    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;
            }
        }

        ...
    }

    ...
    return handled;
}

以上流程相对比较复杂,总结下来就是,先根据onInterceptTouchEvent的结果判断当前的ViewGroup是否拦截,如果拦截了,就从维护的TouchTarget链表中寻找可以消费事件的child,如果不拦截,就遍历所有的子view,直到找到消费事件的子view,并添加到TouchTarget链表中。接下来我们看下dispatchTransformedTouchEvent的实现,代码如下:

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

    ...

    // Perform any necessary transformations and dispatch.
    if (child == null) {
        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());
        }

        handled = child.dispatchTouchEvent(transformedEvent);
    }

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

这里如果child不存在,就交给父级来处理,否则就交给child来处理,但是它们调用的是同一个方法,这个方法属于View,它的实现如下:

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)) {
            result = true;
        }

        if (!result && onTouchEvent(event)) {
            result = true;
        }
    }

    ...

    return result;
}

可以看到,如果我们设置了OnTouchListener,就会调用它的onTouch方法,否则就会由View的onTouchEvent方法来完成。这个方法的实现如下:

public boolean onTouchEvent(MotionEvent event) {
    final float x = event.getX();
    final float y = event.getY();
    final int viewFlags = mViewFlags;
    final int action = event.getAction();
    // 禁用之后的表现
    if ((viewFlags & ENABLED_MASK) == DISABLED) {
        if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
            setPressed(false);
        }
        // A disabled view that is clickable still consumes the touch
        // events, it just doesn't respond to them.
        return (((viewFlags & CLICKABLE) == CLICKABLE
                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE);
    }
    if (mTouchDelegate != null) {
        if (mTouchDelegate.onTouchEvent(event)) {
            return true;
        }
    }

    if (((viewFlags & CLICKABLE) == CLICKABLE ||
            (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) ||
            (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) {
        switch (action) {
            case MotionEvent.ACTION_UP:
                boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
                if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
                    // take focus if we don't have it already and we should in
                    // touch mode.
                    boolean focusTaken = false;
                    if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
                        focusTaken = requestFocus();
                    }

                    if (prepressed) {
                        // The button is being released before we actually
                        // showed it as pressed.  Make it show the pressed
                        // state now (before scheduling the click) to ensure
                        // the user sees it.
                        setPressed(true, x, y);
                    }
                    // 如果不是长按事件,就是单击事件
                    if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
                        // This is a tap, so remove the longpress check
                        removeLongPressCallback();

                        // 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)) {
                                performClick();
                            }
                        }
                    }

                    if (mUnsetPressedState == null) {
                        mUnsetPressedState = new UnsetPressedState();
                    }

                    if (prepressed) {
                        postDelayed(mUnsetPressedState,
                                ViewConfiguration.getPressedStateDuration());
                    } else if (!post(mUnsetPressedState)) {
                        // If the post failed, unpress right now
                        mUnsetPressedState.run();
                    }

                    removeTapCallback();
                }
                mIgnoreNextUpEvent = false;
                break;

            case MotionEvent.ACTION_DOWN:
                mHasPerformedLongPress = false;

                if (performButtonActionOnTouchDown(event)) {
                    break;
                }

                // Walk up the hierarchy to determine if we're inside a scrolling container.
                boolean isInScrollingContainer = isInScrollingContainer();

                // For views inside a scrolling container, delay the pressed feedback for
                // a short period in case this is a scroll.
                if (isInScrollingContainer) {
                    mPrivateFlags |= PFLAG_PREPRESSED;
                    if (mPendingCheckForTap == null) {
                        mPendingCheckForTap = new CheckForTap();
                    }
                    mPendingCheckForTap.x = event.getX();
                    mPendingCheckForTap.y = event.getY();
                    postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
                } else {
                    // Not inside a scrolling container, so show the feedback right away
                    setPressed(true, x, y);
                    // 检查是否长按事件
                    checkForLongClick(0, x, y);
                }
                break;

            case MotionEvent.ACTION_CANCEL:
                setPressed(false);
                removeTapCallback();
                removeLongPressCallback();
                mInContextButtonPress = false;
                mHasPerformedLongPress = false;
                mIgnoreNextUpEvent = false;
                break;

            case MotionEvent.ACTION_MOVE:
                drawableHotspotChanged(x, y);

                // Be lenient about moving outside of buttons
                if (!pointInView(x, y, mTouchSlop)) {
                    // Outside button
                    removeTapCallback();
                    if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
                        // Remove any future long press/tap checks
                        removeLongPressCallback();

                        setPressed(false);
                    }
                }
                break;
        }

        return true;
    }

    return false;
}

这里可以看出,在ACTION_DOWN事件时会先检查是否是长按,然后在ACTION_UP事件时,如果不是长按再确认是点击事件,那么长按事件是何时触发的呢,我们看以下代码:

private void checkForLongClick(int delayOffset, float x, float y) {
    if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
        mHasPerformedLongPress = false;

        ...
        postDelayed(mPendingCheckForLongPress,
                ViewConfiguration.getLongPressTimeout() - delayOffset);
    }
}

private final class CheckForLongPress implements Runnable {
    ...

    @Override
    public void run() {
        if (isPressed() && (mParent != null)
                && mOriginalWindowAttachCount == mWindowAttachCount) {
            if (performLongClick(mX, mY)) {
                mHasPerformedLongPress = true;
            }
        }
    }
}

这里是发送了一个Delayed消息到Handler中,待取得Message之后就会调用performLongClick方法,这里也可以看到,长按的默认触发时间是通过ViewConfiguration#getLongPressTimeout方法获取的,值是500毫秒。也就是说,只要长按,不需要ACTION_UP就能触发事件,这和我们使用手机时的体验一致。

这里我们看到了一堆函数,这些函数统统都有相同的返回值:一个boolean变量。但是这个变量在不同的函数中代表的意义不同,产生的结果也不一样。接下来,我们分两个部分,依次分析它们的区别,这两个部分分别是关于DOWN事件和关于其他事件(如MOVE、UP)。

DOWN事件的传递

onInterceptTouchEvent

我们要首先分析这个方法,是因为它是ViewGroup特有的,对View而言并不需要。这个方法只有在接收到的事件是DOWN,或着已经维护有TouchTarget链表时才会触发,通俗说就是要么接收到了DOWN,要么它有子View消费了DOWN。这时,ViewGroup才有决定是否要拦截此事件的选择,一旦拦截,就意味着之前不在TouchTarget链表里的子View不会再接收到任何事件。

return true:拦截消息,不在TouchTarget链表里的子View不会接收到任何事件
return false:不拦截,将消息分发给子View来处理

dispatchTouchEvent

dispatch是分发的意思,在ViewGroup和View两个类中的表现并不完全一致。对于ViewGroup,它的dispatch决定是自己消费还是交由子View消费,而对于View而言则是自己消费。而相同点在于,只要dispatch最终返回了false,也就是没有消费,就要交给上一层级来完成,最终如果到Activity还没被消费,事件将被丢弃。

不过这里有一点需要注意的是,如果将事件分发给一个最初不在TouchTarget链表中的子View时,那么这个子View对DOWN事件的处理将决定它能否处理其他事件。在上方分析ViewGroup#dispatchTouchEvent时,我们看到只有子View的dispatchTouchEvent返回为true时,才会把它加入到TouchTarget链表里。

return true:表示告诉上一级,已消费
return false:表示没有办法处理消息,交由上一级来完成

onTouchEvent

这里是处理事件的具体地方了,设置OnTouchListener的道理也是一样的,正如上面说到的,这里处理了DOWN事件后如果返回了false,就意味着它无法再处理UP、MOVE等事件。而返回false表示事件在此处并未终止,还要把事件继续传递下去,直到在某个View返回true为止,或者因没有任何View消费而丢弃。

return true:消费事件,终止事件的传输,并可以处理接下来的MOVE、UP等事件
return false:不消费事件,事件将继续传输

MOVE、UP事件的传递

这些事件的传输和DOWN类似,但是最主要在于它受DOWN事件的影响,如果DOWN事件返回false,也就是称没有消费,那么这个View就不能收到这些事件。

Touch事件的机制,在遇见实际的问题时,情况还是比较复杂的,但是它的根本原理就是源码里向我们展示的这一部分,以后分析具体的View时,可能还会有更多的理解,这个知识需要不断去体会,去尝试,才能了然于心。

上一篇:Android源码分析之Activity启动与View绘制流程(二)

下一篇:Android源码分析之Handler

你可能感兴趣的:(Android源码分析之Touch事件分发机制)