学习笔记——深入理解Android Touch事件分发之ViewGroup

Android 中负责用户交互的组件就是Activity,因此我们从Activity入手,分析Touch事件的分发。

本文源码分析基于 Android 5.0,网络上其他的源码分析大多基于 Android 2.2,稍有不同,但本质一样。

Activity.dispatchTouchEvent()说起

/**
 * Called to process touch screen events.  You can override this to
 * intercept all touch screen events before they are dispatched to the
 * window.  Be sure to call this implementation for touch screen events
 * that should be handled normally.
 *
 * @param ev The touch screen event.
 *
 * @return boolean Return true if this event was consumed.
 */
public boolean dispatchTouchEvent(MotionEvent ev) {
    if (ev.getAction() == MotionEvent.ACTION_DOWN) {
        onUserInteraction();
    }
    if (getWindow().superDispatchTouchEvent(ev)) {
        return true;
    }
    return onTouchEvent(ev);
}

当用户点击屏幕与Activity交互而产生Touch事件时,ActivitydispatchTouchEvent()方法就会被调用。

  • 所有的Touch事件都被封装成MotionEvent对象,包括Touch的位置、第几根手指等。
  • Touch事件类型分为ACTION_DOWNACTION_MOVEACTION_UPACTION_POINTER_DOWNACTION_POINTER_UP以及ACTION_CANCEL
  • 每一个完整的事件以ACTION_DOWN开始,ACTION_UP结束。

当事件为ACTION_DOWN时,调用onUserInteraction()方法。

/**
 * Called whenever a key, touch, or trackball event is dispatched to the
 * activity.  Implement this method if you wish to know that the user has
 * interacted with the device in some way while your activity is running.
 * This callback and {@link #onUserLeaveHint} are intended to help
 * activities manage status bar notifications intelligently; specifically,
 * for helping activities determine the proper time to cancel a notfication.
 *
 * <p>All calls to your activity's {@link #onUserLeaveHint} callback will
 * be accompanied by calls to {@link #onUserInteraction}.  This
 * ensures that your activity will be told of relevant user activity such
 * as pulling down the notification pane and touching an item there.
 *
 * <p>Note that this callback will be invoked for the touch down action
 * that begins a touch gesture, but may not be invoked for the touch-moved
 * and touch-up actions that follow.
 *
 * @see #onUserLeaveHint()
 */
public void onUserInteraction() {
}

该方法是一个空方法,可根据需要在Activity中复写该方法。

紧接着往下看到if判断中的getWindow().superDispatchTouchEvent(ev)
getWindow()返回当前Activity的顶层窗口Window对象,查看Window API 的superDispatchTouchEvent()方法

/** 
* Used by custom windows, such as Dialog, to pass the touch screen event 
* further down the view hierarchy. Application developers should 
* not need to implement or call this. 
* 
*/  
public abstract boolean superDispatchTouchEvent(MotionEvent event); 

这是一个抽象方法,我们可以找到Window的子类PhoneWindow查看它的superDispatchTouchEvent()方法。从文档中我们可以看到关于PhoneWindow的一句描述The only existing implementation of this abstract class is android.policy.PhoneWindow, which you should instantiate when needing a Window.

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

该方法调用了mDecorsuperDispatchTouchEvent()方法。mDecorDecorView,Window界面最顶层的View对象。

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

略谈 DecorView

DecorViewPhoneWindow的一个final内部类并且继承FrameLayout,也是Window界面最顶层的View对象。

private final class DecorView extends FrameLayout implements RootViewSurfaceTaker {
    ...
}

我们任意创建一个MainActivity,布局文件如下

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    xmlns:tools="http://schemas.android.com/tools"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    tools:context=".MainActivity" >  

    <TextView  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:text="hello_world" />  

</RelativeLayout>

这里写图片描述

可以看到最顶层的就是PhoneWindow$DecorView

下面我们接着看DecorViewsuperDispatchTouchEvent()方法

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

里面调用了父类FrameLayoutdispatchTouchEvent()方法,而FrameLayout并没有复写dispatchTouchEvent()方法,所以继续查看FrameLayout的父类ViewGroupdispatchTouchEvent()方法。

ViewGroup 的dispatchTouchEvent()方法

/**
 * {@inheritDoc}
 */
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {

    // Consistency verifier for debugging purposes.
    if (mInputEventConsistencyVerifier != null) {
        mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
    }

    boolean handled = false;

    // onFilterTouchEventForSecurity()是一个安全拦截策略,默认返回true,开发者可以继承添加自己的安全策略。
    // 返回true为不过滤,分发下去,false则销毁掉该事件。
    // 方法具体实现是去判断是否被其它窗口遮挡住了,如果遮挡住就要过滤掉该事件。
    if (onFilterTouchEventForSecurity(ev)) {
        // 没有被其它窗口遮住
        final int action = ev.getAction();
        final int actionMasked = action & MotionEvent.ACTION_MASK;

        // 在ACTION_DOWN的时候把所有的状态都重置,作为一系列新事件的开始。
        // Handle an initial 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.

            // 将mFirstTouchTarget置为null,因为是新的一系列手势的开始。
            // mFirstTouchTarget是处理第一个事件的目标。
            cancelAndClearTouchTargets(ev);

            // 重置Touch状态标识
            resetTouchState();
        }

        // Check for interception.
        final boolean intercepted;
        if (actionMasked == MotionEvent.ACTION_DOWN || mFirstTouchTarget != null) {
        // 当事件为ACTION_DOWN或者已经找到能够消费Touch事件的目标组件时,if判断成立。
        // 如果ACTION_DOWN事件被Child View消费(即mFirstTouchTarget != null),后续的
        // ACTION_MOVE以及ACTION_UP事件发生时,仍会执行该代码段判断是否需要拦截Touch事件。

            // 标记事件不允许被拦截的标志位,默认是false。
            // 该值可以通过Child View调用requestDisallowInterceptTouchEvent(true)方法
            // 通知Parent View不要拦截该View上的事件。
            // Child View可以禁止Parent View拦截MOVE和UP事件,但是无法禁止Parent View拦截DOWN事件。
            // 因为在ACTION_DOWN事件发生时,会在前面的resetTouchState()方法
            // 来重置FLAG_DISALLOW_INTERCEPT的值。
            // 所以ACTION_DOWN事件发生时,ViewGroup总会调用onInterceptTouchEvent()判断是否拦截该事件。
            final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
            if (!disallowIntercept) {// disallowIntercept为false,即Touch事件可以被拦截。

                // 调用onInterceptTouchEvent()判断是否拦截该Touch事件,返回true表示拦截。
                intercepted = onInterceptTouchEvent(ev);
                ev.setAction(action); // restore action in case it was changed
            } else {
                // Child View禁止Parent View拦截Touch事件。
                // 所以Parent View就不会拦截该事件。
                intercepted = false;
            }
        } else {
            // 没有找到Child View来处理该事件,而且也不是一个新的ACTION_DOWN事件(新事件的开始), 
            // 我们应该拦截下他。
            // There are no touch targets and this action is not an initial down
            // so this view group continues to intercept touches.
            intercepted = true;
        }

        // Check for cancelation.
        // 检查当前是否是Cancel事件或者是有Cancel标记。
        final boolean canceled = resetCancelNextUpFlag(this)
                || actionMasked == MotionEvent.ACTION_CANCEL;

        // Update list of touch targets for pointer down, if needed. 
        // 这行代码为是否需要将当前的触摸事件分发给多个子View,
        // 默认为true,分发给多个View(比如几个Child View位置重叠)。
        final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;

        // 保存当前要分发给的目标View。
        TouchTarget newTouchTarget = null;
        boolean alreadyDispatchedToNewTouchTarget = false;

        if (!canceled && !intercepted) {// 如果没取消也不拦截,进入方法内部。

            // 下面这部分代码其实就是找到该事件位置下的View, 并且与pointerID关联。
            if (actionMasked == MotionEvent.ACTION_DOWN
                    || (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)
                    || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {// DOWN事件处理

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

                    // 依据坐标来寻找Child View接收Touch事件。
                    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 = buildOrderedChildList();
                    final boolean customOrder = preorderedList == null
                            && isChildrenDrawingOrderEnabled();

                    // 遍历Child View进行事件分发。
                    final View[] children = mChildren;
                    for (int i = childrenCount - 1; i >= 0; i--) {
                        final int childIndex = customOrder
                                ? getChildDrawingOrder(childrenCount, i) : i;
                        final View child = (preorderedList == null)
                                ? children[childIndex] : preorderedList.get(childIndex);

                        // canViewReceivePointerEvents()方法判断这个View
                        // 是否可见或者在播放动画,只有这两种情况下可以接受事件的分发。

                        // isTransformedTouchPointInView判断这个事件的坐标值是否在该View内。
                        if (!canViewReceivePointerEvents(child)
                                || !isTransformedTouchPointInView(x, y, child, null)) {
                            continue;
                        }

                        // 找到该Child View对应的在mFristTouchTarget中的存储的目标,
                        // 判断这个View是否为之前mFristTouchTarget中的View了。
                        // 如果找不到就返回null, 这种情况适用于多点触摸, 比如在同一个View上按下了多根手指。
                        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;
                            // 找到该View了,跳出循环。
                            break;
                        }
                        // 如果上面没有break,则newTouchTarget为null,
                        // 说明上面我们找到的Child View和之前的肯定不是同一个了,是新增的。
                        // 比如多点触摸的时候,一个手指按在了这个View上,另一个手指按在了另一个View上。

                        resetCancelNextUpFlag(child);

                        // 调用dispatchTransformedTouchEvent()将Touch事件分发给Child View。
                        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();

                            // 赋值成现在的Child View对应的值,并且会把mFirstTouchTarget也改成该值。
                            newTouchTarget = addTouchTarget(child, idBitsToAssign);

                            // 已经分发给Child View了,不用再继续循环。
                            alreadyDispatchedToNewTouchTarget = true;
                            break;
                        }
                    }
                    if (preorderedList != null) preorderedList.clear();
                }

                // 遍历完Child View之后没有找到新的可以分发该事件的Child View,
                // 即newTouchTarget == null,
                // 那我们只能用上一次的分发对象了。(适用于多点触摸的情况)
                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;
                }
            }
        }

        /**
         * 经过上面对于ACTION_DOWN的处理后mFirstTouchTarget有两种情况:
         * 1 mFirstTouchTarget == null
         * 2 mFirstTouchTarget != null
         * 
         * 当然如果不是ACTION_DOWN就不会经过上面较繁琐的流程
         * 而是从此处开始执行,比如ACTION_MOVE和ACTION_UP
         */ 

        // Dispatch to touch targets.
        if (mFirstTouchTarget == null) {
            // 没有找到能够消费touch事件的子组件或Touch事件被拦截了。

            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;
                // 找到了新的Child View,并且这个是新加的对象,上面已经处理过了。
                if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
                    handled = true;
                } else {
                    // 否则都调用dispatchTransformedTouchEvent处理,传递给child
                    final boolean cancelChild = resetCancelNextUpFlag(target.child)
                            || intercepted;

                    // 对于非ACTION_DOWN事件继续传递给目标子组件进行处理。
                    if (dispatchTransformedTouchEvent(ev, cancelChild,
                            target.child, target.pointerIdBits)) {
                        handled = true;
                    }

                    // 如果onInterceptTouchEvent返回true就会遍历mFirstTouchTarget全部给销毁,
                    // 这就是为什么onInterceptTouchEvent返回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;
}

mFirstTouchTarget真正的赋值过程是在addTouchTarget内部完成的

private TouchTarget addTouchTarget(View child, int pointerIdBits) {
    TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
    target.next = mFirstTouchTarget;
    mFirstTouchTarget = target;
    return target;
}

可以看出mFirstTouchTarget其实是一种单链表结构,mFirstTouchTarget是否被赋值,直接影响到ViewGroup对事件的拦截策略。

总结一下ViewGroupdispatchTouchEvent()方法:

  • Step 1
    因为ACTION_DOWN是一系列 Touch 事件的开端,在 Touch 事件为ACTION_DOWN, 进行一些初始化工作和还原操作。

  • Step 2
    检查ViewGroup是否需要拦截 Touch 事件。

  • Step 3
    检查Cancel

  • Step 4
    如果 Touch 事件没有被拦截也没有被取消,那么ViewGroup将类型为ACTION_DOWN的 Touch 事件分发给 Child View。

  • Step 5
    分发ACTION_MOVEACTION_UP事件,如果ACTION_DOWN事件在上一步中没有被处理,将会在此被处理。

  • Step 6
    清理数据和状态还原。

ViewGroup 将ACTION_DOWN分发给 Child View,如果 Child View 没有消费该事件,那么当ACTION_MOVEACTION_UP到来的时候系统不会将 Touch 事件派发给该 Child View。

在 Step 4 中如果 Child View 处理了 Touch 事件那么mFirstTouchTarget != null,如果 Child View 没有处理 Touch 事件 (被 Parent View 拦截或本身没有消费事件),那么mFirstTouchTarget == null。当ACTION_MOVEACTION_UP到来时, 在 Step 5 中就会进行判断。mFirstTouchTarget == null,那么 ViewGroup 自身会处理 Touch;如果mFirstTouchTarget != null那么继续由 mFirstTouchTarget 处理 Touch 事件。

略谈dispatchTransformedTouchEvent()方法

在上面分析中,我们看到,当 Parent View 找到目标 Child View 之后,会通过dispatchTransformedTouchEvent()方法将 Touch 事件进行分发。

/**
 * Transforms a motion event into the coordinate space of a particular child view,
 * filters out irrelevant pointer ids, and overrides its action if necessary.
 * If child is null, assumes the MotionEvent will be sent to this ViewGroup instead.
 */
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();

    // 这就是为什么Touch事件被拦截之后,之前处理过该事件的View会收到CANCEL.
    if (cancel || oldAction == MotionEvent.ACTION_CANCEL) {
        event.setAction(MotionEvent.ACTION_CANCEL);
        if (child == null) {
            handled = super.dispatchTouchEvent(event);
        } else {
            // Child View去处理,如果Child View仍然是ViewGroup那还是同样的递归处理。
            // 如果Child View是Normal View,Normal View的dispatchTouchEveent()会调用onTouchEvent()。
            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) {
        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;
}
  • 如果ViewGroup拦截了 Touch 事件或者 Child View 不能消耗掉 Touch 事件,那么ViewGroup会在其自身的onTouch()onTouchEvent()中处理 Touch 事件。
  • 如果 Child View 消耗了 Touch 事件,Parent View 就不能再处理 Touch 事件。

总结

Touch 事件的传递顺序为:
Activity –> 外层ViewGroup –> 内层ViewGroup –> View

Touch 事件的消费顺序为 :
View –> 内层ViewGroup –> 外层ViewGroup –> Activity

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值