Android开发

【Android 事件分发】事件分发源码分析 ( ViewGroup 事件传递机制 六 )

本文主要是介绍【Android 事件分发】事件分发源码分析 ( ViewGroup 事件传递机制 六 ),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Android 事件分发 系列文章目录


【Android 事件分发】事件分发源码分析 ( 驱动层通过中断传递事件 | WindowManagerService 向 View 层传递事件 )
【Android 事件分发】事件分发源码分析 ( Activity 中各层级的事件传递 | Activity -> PhoneWindow -> DecorView -> ViewGroup )
【Android 事件分发】事件分发源码分析 ( ViewGroup 事件传递机制 一 )
【Android 事件分发】事件分发源码分析 ( ViewGroup 事件传递机制 二 )
【Android 事件分发】事件分发源码分析 ( ViewGroup 事件传递机制 三 )
【Android 事件分发】事件分发源码分析 ( ViewGroup 事件传递机制 四 | View 事件传递机制 )
【Android 事件分发】事件分发源码分析 ( ViewGroup 事件传递机制 五 )
【Android 事件分发】事件分发源码分析 ( ViewGroup 事件传递机制 六 )


文章目录

  • Android 事件分发 系列文章目录
  • 一、按下触摸事件记录
  • 二、完整的触摸事件处理机制
  • 三、ViewGroup | dispatchTouchEvent 方法返回
  • 四、ViewGroup 事件分发相关源码
  • 五、View 事件分发相关源码





一、按下触摸事件记录



在上一篇博客 【Android 事件分发】事件分发源码分析 ( ViewGroup 事件传递机制 五 ) 中 , 着重分析了 ViewGroup 事件分发中 , 触摸事件没有被消费 , 或被父容器拦截的情况 ;

这里再分析下触摸事件被消费之后的 , 触摸事件记录过程 ;

触摸事件如果成功被消费 , 则 dispatchTransformedTouchEvent 方法返回 true ;

对应的会调用 addTouchTarget 方法 , 创建 TouchTarget 对象 , 赋值给 newTouchTarget 成员变量 ;

newTouchTarget = addTouchTarget(child, idBitsToAssign)

TouchTarget 代表了个触摸事件 , 每个 TouchTarget 中都封装了消费该触摸事件的 View 组件 ;

        // The touched child view.
        // 当前 View 对象 
        public View child;

TouchTarget 经过优化后 , 以链表形式存储 , 每个 TouchTarget 都定义了一个 next 成员变量 , 指向下一个 TouchTarget 被消费的触摸事件 ;

        // The next target in the target list.
        // 链表操作 , 该引用指向下一个触摸事件 
        public TouchTarget next;

相关源码 :

@UiThread
public abstract class ViewGroup extends View implements ViewParent, ViewManager {
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
		...
                            // 正式开始分发触摸事件
                            // 处理以下两种情况 : 
                            // ① 情况一 : 子控件触摸事件返回 true 
                            // ② 情况二 : 子控件触摸事件返回 false 
                            if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
                                // Child wants to receive touch within its bounds.
                                // 如果返回值为 true , 说明该事件已经被消费了 
                                // 此时记录这个已经被消费的事件 
                                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();
                                // 记录消费事件 
                                // 添加触摸目标 
                                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();
                    }

					// 如果上述事件分发方法 dispatchTransformedTouchEvent 返回 true 
					// 就会创建 newTouchTarget 值 , 该值不会为空 , 同时 mFirstTouchTarget 不为空
					// 如果上述事件分发方法 dispatchTransformedTouchEvent 返回 false 
					// 此时 newTouchTarget 值 , 就会为空 , 同时 mFirstTouchTarget 为空 
                    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;
                    }
                }
            }

			// 如果事件被消费 , 事件分发方法 dispatchTransformedTouchEvent 返回 true 
			// 就会创建 newTouchTarget 值 , 该值不会为空 , 同时 mFirstTouchTarget 不为空
			// 反之
			// 如果上述事件分发方法 dispatchTransformedTouchEvent 返回 false 
			// 此时 newTouchTarget 值 , 就会为空 , 同时 mFirstTouchTarget 为空 
			// 
			// 还有一个逻辑就是 , 如果该事件被父容器拦截 , mFirstTouchTarget 也是 null 值
			// 调用 dispatchTransformedTouchEvent , 但是传入的子组件时 null 
			// 在 dispatchTransformedTouchEvent 方法中触发调用 if (child == null) 分支的 
			// handled = super.dispatchTouchEvent(event) 方法 , 调用父类的事件分发方法 
            // Dispatch to touch targets.
            if (mFirstTouchTarget == null) {
            	// 事件没有被消费的分支 
                // 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;

						// 转发下一个触摸事件 
                        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;
    }

    /**
     * Adds a touch target for specified child to the beginning of the list.
     * Assumes the target child is not already present.
     */
    private TouchTarget addTouchTarget(@NonNull View child, int pointerIdBits) {
        final TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
        target.next = mFirstTouchTarget;
        mFirstTouchTarget = target;
        return target;
    }
}




二、完整的触摸事件处理机制



完整触摸事件 :

一个完整的触摸动作 , 由 1 1 1 次 按下触摸事件 , 若干次 移动触摸事件 , 1 1 1 次 抬起触摸事件 组成 ,

1 1 1 个触摸动作只有 1 1 1 次按下操作 , 并且是整个触摸动作的起始 触摸事件 ;

一个完整的动作 , 只有第一次按下 , 才执行 子组件的 排序 , 遍历 , 事件分发 等操作 ; 第一次按下后 , 手指按着移动 , 属于第2次以及之后的第n次动作 , 不再走该分支 , 直接执行该分支后面的代码 ;

这里在第 1 1 1 次按下时 , 创建触摸事件记录 TouchTarget ; 假如当前动作时按下以后的移动/抬起动作 , 则跳过上面的分支 , 直接执行后面的代码逻辑 , 按下之后 mFirstTouchTarget 肯定不为空 ;


TouchTarget 事件记录封装 :

TouchTarget 对象对应着一个完整的动作 , 该动作包含 1 个按下事件 , 若干 移动 事件 , 1 个抬起事件 ;

第一次按下 , 负责构建 TouchTarget 链表 , 将消费事件的 View 组件封装到 TouchTarget 中 ;

然后的移动/抬起操作 , 不再重复的创建 TouchTarget 对象了 ; 直接使用第一次按下的 TouchTarget 对象作为当前动作的标识 , 直接向该 TouchTarget 对象中的 View 组件分发事件 ;

这也是我们按下按钮时 , 即使将手指按着移出边界 , 按钮也处于按下状态 ;


相关源码 :

public abstract class ViewGroup extends View implements ViewParent, ViewManager {

    // First touch target in the linked list of touch targets.
    private TouchTarget mFirstTouchTarget;

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
				// 判断是否是按下操作 
				// 一个完整的动作 , 只有第一次按下 , 才执行下面的逻辑 
				// 第一次按下后 , 手指按着移动 , 属于第2次以及之后的第n次动作 , 不再走该分支 
				// 直接执行该分支后面的代码 
                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;

					// 计算 ViewGroup 父容器下面有多少个子 View 组件 ; 
                    final int childrenCount = mChildrenCount;
                    // TouchTarget newTouchTarget = null; 在上面声明为空 , 此处肯定为 null ; 
                    // childrenCount 子组件个数不为 0 
                    // 如果子组件个数为 0 , 则不走下一段代码 , 如果子组件个数大于 0 , 则执行下一段代码 ; 
                    // 说明下面的代码块中处理的是 ViewGroup 中子组件的事件分发功能 ; 
                    if (newTouchTarget == null && childrenCount != 0) {
                    	// 获取单个手指的 x,y 坐标 
                        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.
                        // 子组件排序 , 按照 Z 轴排列的层级 , 从上到下进行排序 , 
                        // 控件会相互重叠 , Z 轴的排列次序上 , 
                        // 顶层的组件优先获取到触摸事件 
                        final ArrayList<View> preorderedList = buildTouchDispatchChildList();
                        final boolean customOrder = preorderedList == null
                                && isChildrenDrawingOrderEnabled();
                        final View[] children = mChildren;
	
						// 倒序遍历 按照 Z 轴的上下顺序 , 排列好的组件 
						// 先遍历的 Z 轴方向上 , 放在最上面的组件 , 也就是顶层组件 
                        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;
                            }

							// X 控件范围 A , 如果手指按在 B 范围 , 不会触发 X 控件的事件 
							// 判定当前的组件是否可见 , 是否处于动画过程中 
							// ① canViewReceivePointerEvents 判定组件是否可见 , 会否处于动画 
							// ② isTransformedTouchPointInView 判定手指是否在控件上面 ; 
							// 上述两种情况 , 不触发事件 
                            if (!canViewReceivePointerEvents(child)
                                    || !isTransformedTouchPointInView(x, y, child, null)) {
                                ev.setTargetAccessibilityFocus(false);
                                // 不触发事件 
                                continue;
                            }
							
							// 截止到此处 , 可以获取子组件进行操作   

							// 提取当前的子组件 
							// 第一次执行 getTouchTarget 代码时 , 是没有 mFirstTouchTarget 的
							// 此时第一次返回 null 
                            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);
                            // 正式开始分发触摸事件
                            // 处理以下两种情况 : 
                            // ① 情况一 : 子控件触摸事件返回 true 
                            // ② 情况二 : 子控件触摸事件返回 false 
                            if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
                                // Child wants to receive touch within its bounds.
                                // 如果返回值为 true , 说明该事件已经被消费了 
                                // 此时记录这个已经被消费的事件 
                                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();
                                // 记录消费事件 
                                // 添加触摸目标 
                                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();
                    }


			// 上面的分支是只有第一次按下时才执行的 
			// 假如当前动作时按下以后的移动/抬起动作 
			// 则跳过上面的分支 , 直接执行后面的代码逻辑 
			// 按下之后 mFirstTouchTarget 肯定不为空 
		

			// 如果事件被消费 , 事件分发方法 dispatchTransformedTouchEvent 返回 true 
			// 就会创建 newTouchTarget 值 , 该值不会为空 , 同时 mFirstTouchTarget 不为空
			// 反之
			// 如果上述事件分发方法 dispatchTransformedTouchEvent 返回 false 
			// 此时 newTouchTarget 值 , 就会为空 , 同时 mFirstTouchTarget 为空 
			// 
			// 还有一个逻辑就是 , 如果该事件被父容器拦截 , mFirstTouchTarget 也是 null 值
			// 调用 dispatchTransformedTouchEvent , 但是传入的子组件时 null 
			// 在 dispatchTransformedTouchEvent 方法中触发调用 if (child == null) 分支的 
			// handled = super.dispatchTouchEvent(event) 方法 , 调用父类的事件分发方法 
            // Dispatch to touch targets.
            if (mFirstTouchTarget == null) {
            	// 事件没有被消费的分支 
                // No touch targets so treat this as an ordinary view.
                handled = dispatchTransformedTouchEvent(ev, canceled, null,
                        TouchTarget.ALL_POINTER_IDS);
            } else {
				// TouchTarget 对象对应着一个完整的动作 , 该动作包含 1 个按下事件 , 若干 移动 事件 , 1 个抬起事件 ; 

            	// 第一次按下 , 负责构建 TouchTarget 链表 , 将消费事件的 View 组件封装到 TouchTarget  中
            	// 然后的移动/抬起操作 , 不再重复的创建 TouchTarget 对象了 
            	// 直接使用第一次按下的 TouchTarget 对象作为当前动作的标识 
            	// 直接向该 TouchTarget 对象中的 View 组件分发事件 
            	// 这也是我们按下按钮时 , 即使将手指按着移出边界 , 按钮也处于按下状态 ; 



            	// 事件被消费的分支 , 事件消费成功 , 会走这个分支 
                // Dispatch to touch targets, excluding the new touch target if we already
                // dispatched to it.  Cancel touch targets if necessary.
                TouchTarget predecessor = null;

				// 将当前所有的消费的事件以及消费的 View 组件做成了一个链表 
                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;

						// 找到了 View , 开始分发触摸事件 
                        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;
                }
            }
	}
}




三、ViewGroup | dispatchTouchEvent 方法返回



在 【Android 事件分发】事件分发源码分析 ( Activity 中各层级的事件传递 | Activity -> PhoneWindow -> DecorView -> ViewGroup ) 博客中分析了从 Activity -> PhoneWindow -> DecorView -> ViewGroup 的调用链 ;


Activity | dispatchTouchEvent 方法调用 PhoneWindow | superDispatchTouchEvent 方法 ,
PhoneWindow | superDispatchTouchEvent 方法调用 DecorView | superDispatchTouchEvent 方法 ,
DecorView | superDispatchTouchEvent 方法调用 ViewGroup | dispatchTouchEvent 方法 ;


ViewGroup 的 dispatchTouchEvent 事件分发方法执行完毕后 ,
先返回到 DecorView | superDispatchTouchEvent 方法 ,
然后返回到 PhoneWindow | superDispatchTouchEvent 方法 .
最终返回到 Activity 的 dispatchTouchEvent ;


如果在 Activity 的 dispatchTouchEvent 方法中 , PhoneWindow 的 superDispatchTouchEvent 方法的返回值是 true , 即 ViewGroup 的 dispatchTouchEvent 方法返回 true ;

则直接返回 , 不再向后执行 ;

		// getWindow() 获取的是 PhoneWindow 窗口 
		// 调用 PhoneWindow 的 superDispatchTouchEvent ; 
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }

相关源码 :

public class Activity extends ContextThemeWrapper
        implements LayoutInflater.Factory2,
        Window.Callback, KeyEvent.Callback,
        OnCreateContextMenuListener, ComponentCallbacks2,
        Window.OnWindowDismissedCallback, WindowControllerCallback,
        AutofillManager.AutofillClient {
    /**
     * 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();
        }
		
		// getWindow() 获取的是 PhoneWindow 窗口 
		// 调用 PhoneWindow 的 superDispatchTouchEvent ; 
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }
    
    public void onUserInteraction() {
    }
}

源码路径 : /frameworks/base/core/java/android/app/Activity.java





四、ViewGroup 事件分发相关源码



@UiThread
public abstract class ViewGroup extends View implements ViewParent, ViewManager {

    // First touch target in the linked list of touch targets.
    private TouchTarget mFirstTouchTarget;

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

		// 是否按下操作 , 最终的对外返回结果 , 该方法的最终返回值 
        boolean handled = false;
        if (onFilterTouchEventForSecurity(ev)) {
            final int action = ev.getAction();
            final int actionMasked = action & MotionEvent.ACTION_MASK;

            // 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.
                cancelAndClearTouchTargets(ev);
                // 如果是第一次按下 , 那么重置触摸状态 
                resetTouchState();
            }

            // Check for interception.
            // 判定是否拦截 
            // 用于多点触控按下操作的判定 
            final boolean intercepted;
            if (actionMasked == MotionEvent.ACTION_DOWN
                    || mFirstTouchTarget != null) {
                // 判断是否需要拦截 , 可以使用 requestDisallowInterceptTouchEvent 方法进行设置
                final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
                if (!disallowIntercept) {
                	// 进行事件拦截 
                	// 该 onInterceptTouchEvent 方法只返回是否进行事件拦截 , 返回一个布尔值 , 没有进行具体的事件拦截 
                	// 是否进行拦截 , 赋值给了 intercepted 局部变量 
                	// 该值决定是否进行拦截 
                    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.
            // 检查是否取消操作 , 手指是否移除了组件便捷 ; 
            // 一般情况默认该值是 false ; 
            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;
            // 注意此处 newTouchTarget 为空 
            TouchTarget newTouchTarget = null;
            boolean alreadyDispatchedToNewTouchTarget = false;

			// 此处判定 , 是否拦截 
			// 假定不取消 , 也不拦截 
			// canceled 和 intercepted 二者都是 false , 才不能拦截 ; 
            if (!canceled && !intercepted) {

                // If the event is targeting accessibility 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;

				// 判断是否是按下操作 
				// 一个完整的动作 , 只有第一次按下 , 才执行下面的逻辑 
				// 第一次按下后 , 手指按着移动 , 属于第2次以及之后的第n次动作 , 不再走该分支 
				// 直接执行该分支后面的代码 
                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);

					// 计算 ViewGroup 父容器下面有多少个子 View 组件 ; 
                    final int childrenCount = mChildrenCount;
                    // TouchTarget newTouchTarget = null; 在上面声明为空 , 此处肯定为 null ; 
                    // childrenCount 子组件个数不为 0 
                    // 如果子组件个数为 0 , 则不走下一段代码 , 如果子组件个数大于 0 , 则执行下一段代码 ; 
                    // 说明下面的代码块中处理的是 ViewGroup 中子组件的事件分发功能 ; 
                    if (newTouchTarget == null && childrenCount != 0) {
                    	// 获取单个手指的 x,y 坐标 
                        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.
                        // 子组件排序 , 按照 Z 轴排列的层级 , 从上到下进行排序 , 
                        // 控件会相互重叠 , Z 轴的排列次序上 , 
                        // 顶层的组件优先获取到触摸事件 
                        final ArrayList<View> preorderedList = buildTouchDispatchChildList();
                        final boolean customOrder = preorderedList == null
                                && isChildrenDrawingOrderEnabled();
                        final View[] children = mChildren;
	
						// 倒序遍历 按照 Z 轴的上下顺序 , 排列好的组件 
						// 先遍历的 Z 轴方向上 , 放在最上面的组件 , 也就是顶层组件 
                        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;
                            }

							// X 控件范围 A , 如果手指按在 B 范围 , 不会触发 X 控件的事件 
							// 判定当前的组件是否可见 , 是否处于动画过程中 
							// ① canViewReceivePointerEvents 判定组件是否可见 , 会否处于动画 
							// ② isTransformedTouchPointInView 判定手指是否在控件上面 ; 
							// 上述两种情况 , 不触发事件 
                            if (!canViewReceivePointerEvents(child)
                                    || !isTransformedTouchPointInView(x, y, child, null)) {
                                ev.setTargetAccessibilityFocus(false);
                                // 不触发事件 
                                continue;
                            }
							
							// 截止到此处 , 可以获取子组件进行操作   

							// 提取当前的子组件 
							// 第一次执行 getTouchTarget 代码时 , 是没有 mFirstTouchTarget 的
							// 此时第一次返回 null 
                            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);
                            // 正式开始分发触摸事件
                            // 处理以下两种情况 : 
                            // ① 情况一 : 子控件触摸事件返回 true 
                            // ② 情况二 : 子控件触摸事件返回 false 
                            if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
                                // Child wants to receive touch within its bounds.
                                // 如果返回值为 true , 说明该事件已经被消费了 
                                // 此时记录这个已经被消费的事件 
                                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();
                                // 记录消费事件 
                                // 添加触摸目标 
                                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();
                    }

					// 如果上述事件分发方法 dispatchTransformedTouchEvent 返回 true 
					// 就会创建 newTouchTarget 值 , 该值不会为空 , 同时 mFirstTouchTarget 不为空
					// 如果上述事件分发方法 dispatchTransformedTouchEvent 返回 false 
					// 此时 newTouchTarget 值 , 就会为空 , 同时 mFirstTouchTarget 为空 
                    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 肯定不为空 
		

			// 如果事件被消费 , 事件分发方法 dispatchTransformedTouchEvent 返回 true 
			// 就会创建 newTouchTarget 值 , 该值不会为空 , 同时 mFirstTouchTarget 不为空
			// 反之
			// 如果上述事件分发方法 dispatchTransformedTouchEvent 返回 false 
			// 此时 newTouchTarget 值 , 就会为空 , 同时 mFirstTouchTarget 为空 
			// 
			// 还有一个逻辑就是 , 如果该事件被父容器拦截 , mFirstTouchTarget 也是 null 值
			// 调用 dispatchTransformedTouchEvent , 但是传入的子组件时 null 
			// 在 dispatchTransformedTouchEvent 方法中触发调用 if (child == null) 分支的 
			// handled = super.dispatchTouchEvent(event) 方法 , 调用父类的事件分发方法 
            // Dispatch to touch targets.
            if (mFirstTouchTarget == null) {
            	// 事件没有被消费的分支 
                // No touch targets so treat this as an ordinary view.
                handled = dispatchTransformedTouchEvent(ev, canceled, null,
                        TouchTarget.ALL_POINTER_IDS);
            } else {
				// TouchTarget 对象对应着一个完整的动作 , 该动作包含 1 个按下事件 , 若干 移动 事件 , 1 个抬起事件 ; 

            	// 第一次按下 , 负责构建 TouchTarget 链表 , 将消费事件的 View 组件封装到 TouchTarget  中
            	// 然后的移动/抬起操作 , 不再重复的创建 TouchTarget 对象了 
            	// 直接使用第一次按下的 TouchTarget 对象作为当前动作的标识 
            	// 直接向该 TouchTarget 对象中的 View 组件分发事件 
            	// 这也是我们按下按钮时 , 即使将手指按着移出边界 , 按钮也处于按下状态 ; 



            	// 事件被消费的分支 , 事件消费成功 , 会走这个分支 
                // Dispatch to touch targets, excluding the new touch target if we already
                // dispatched to it.  Cancel touch targets if necessary.
                TouchTarget predecessor = null;

				// 将当前所有的消费的事件以及消费的 View 组件做成了一个链表 
                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;

						// 找到了 View , 开始分发触摸事件 
                        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);
        }
        // ViewGroup 的 事件分发方法执行完毕后 
        // 返回到 Activity 的 dispatchTouchEvent 
        return handled;
    }

    /* Describes a touched view and the ids of the pointers that it has captured.
     *
     * This code assumes that pointer ids are always in the range 0..31 such that
     * it can use a bitfield to track which pointer ids are present.
     * As it happens, the lower layers of the input dispatch pipeline also use the
     * same trick so the assumption should be safe here...
     * 可以理解成触摸事件的消费目标 
     */
    private static final class TouchTarget {
        private static final int MAX_RECYCLED = 32;
        private static final Object sRecycleLock = new Object[0];
        private static TouchTarget sRecycleBin;
        private static int sRecycledCount;

        public static final int ALL_POINTER_IDS = -1; // all ones

        // The touched child view.
        // 当前 View 对象 
        public View child;

        // The combined bit mask of pointer ids for all pointers captured by the target.
        public int pointerIdBits;

        // The next target in the target list.
        // 链表操作 , 该引用指向下一个触摸事件 
        public TouchTarget next;

        private TouchTarget() {
        }

        public static TouchTarget obtain(@NonNull View child, int pointerIdBits) {
            if (child == null) {
                throw new IllegalArgumentException("child must be non-null");
            }

            final TouchTarget target;
            synchronized (sRecycleLock) {
                if (sRecycleBin == null) {
                    target = new TouchTarget();
                } else {
                    target = sRecycleBin;
                    sRecycleBin = target.next;
                     sRecycledCount--;
                    target.next = null;
                }
            }
            target.child = child;
            target.pointerIdBits = pointerIdBits;
            return target;
        }

        public void recycle() {
            if (child == null) {
                throw new IllegalStateException("already recycled once");
            }

            synchronized (sRecycleLock) {
                if (sRecycledCount < MAX_RECYCLED) {
                    next = sRecycleBin;
                    sRecycleBin = this;
                    sRecycledCount += 1;
                } else {
                    next = null;
                }
                child = null;
            }
        }
    }

    @Override
    public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
		// disallowIntercept 存在一个默认值 , 如果值为默认值 , 直接退出 
        if (disallowIntercept == ((mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0)) {
            // We're already in this state, assume our ancestors are too
            return;
        }

		// 如果不是默认值 , 则进行相应更改 
		// 最终的值影响 mGroupFlags 是 true 还是 false 
        if (disallowIntercept) {
            mGroupFlags |= FLAG_DISALLOW_INTERCEPT;
        } else {
            mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;
        }

        // Pass it up to our parent
        if (mParent != null) {
            mParent.requestDisallowInterceptTouchEvent(disallowIntercept);
        }
    }

    public boolean onInterceptTouchEvent(MotionEvent ev) {
    	// 该方法只返回是否进行事件拦截 , 返回一个布尔值 , 没有进行具体的事件拦截 
        if (ev.isFromSource(InputDevice.SOURCE_MOUSE)
                && ev.getAction() == MotionEvent.ACTION_DOWN
                && ev.isButtonPressed(MotionEvent.BUTTON_PRIMARY)
                && isOnScrollbarThumb(ev.getX(), ev.getY())) {
            return true;
        }
        return false;
    }

    /**
     * Provide custom ordering of views in which the touch will be dispatched.
     * 按照事件传递的顺序进行组件排序 
     *
     * This is called within a tight loop, so you are not allowed to allocate objects, including
     * the return array. Instead, you should return a pre-allocated list that will be cleared
     * after the dispatch is finished.
     * @hide
     */
    public ArrayList<View> buildTouchDispatchChildList() {
        return buildOrderedChildList();
    }

    /**
     * Populates (and returns) mPreSortedChildren with a pre-ordered list of the View's children,
     * sorted first by Z, then by child drawing order (if applicable). This list must be cleared
     * after use to avoid leaking child Views.
     *
     * Uses a stable, insertion sort which is commonly O(n) for ViewGroups with very few elevated
     * children.
     */
    ArrayList<View> buildOrderedChildList() {
        final int childrenCount = mChildrenCount;
        if (childrenCount <= 1 || !hasChildWithZ()) return null;

        if (mPreSortedChildren == null) {
            mPreSortedChildren = new ArrayList<>(childrenCount);
        } else {
            // callers should clear, so clear shouldn't be necessary, but for safety...
            mPreSortedChildren.clear();
            mPreSortedChildren.ensureCapacity(childrenCount);
        }

        final boolean customOrder = isChildrenDrawingOrderEnabled();
        // 下面的组件排序的核心逻辑 
        // 获取当前所有组件的子组件的 Z 轴的深度 
        // 按照 Z 轴深度进行排序 
        // Z 轴方向上 , 对于事件传递 , 上面的组件优先级高于被覆盖的下面的组件优先级
        for (int i = 0; i < childrenCount; i++) {
            // add next child (in child order) to end of list
            final int childIndex = getAndVerifyPreorderedIndex(childrenCount, i, customOrder);
            final View nextChild = mChildren[childIndex];
            final float currentZ = nextChild.getZ();

            // insert ahead of any Views with greater Z
            // 计算当前遍历的组件应该被放到的索引位置
            int insertIndex = i;
            while (insertIndex > 0 && mPreSortedChildren.get(insertIndex - 1).getZ() > currentZ) {
                insertIndex--;
            }
            // 将当前遍历的组件插入到指定索引位置上 
            mPreSortedChildren.add(insertIndex, nextChild);
        }
        return mPreSortedChildren;
    }

	// 获取排序后的子组件的索引值
    private int getAndVerifyPreorderedIndex(int childrenCount, int i, boolean customOrder) {
        final int childIndex;
        if (customOrder) {
            final int childIndex1 = getChildDrawingOrder(childrenCount, i);
            if (childIndex1 >= childrenCount) {
                throw new IndexOutOfBoundsException("getChildDrawingOrder() "
                        + "returned invalid index " + childIndex1
                        + " (child count is " + childrenCount + ")");
            }
            childIndex = childIndex1;
        } else {
            childIndex = i;
        }
        return childIndex;
    }

	// 获取索引值对应的组件 
    private static View getAndVerifyPreorderedView(ArrayList<View> preorderedList, View[] children,
            int childIndex) {
        final View child;
        if (preorderedList != null) {
            child = preorderedList.get(childIndex);
            if (child == null) {
                throw new RuntimeException("Invalid preorderedList contained null child at index "
                        + childIndex);
            }
        } else {
            child = children[childIndex];
        }
        return child;
    }

    /**
     * Returns true if a child view can receive pointer events.
     * 判定控件是否可见 / 是否处于动画中 
     * @hide
     */
    private static boolean canViewReceivePointerEvents(@NonNull View child) {
        return (child.mViewFlags & VISIBILITY_MASK) == VISIBLE
                || child.getAnimation() != null;
    }

    /**
     * Returns true if a child view contains the specified point when transformed
     * into its coordinate space.
     * Child must not be null.
     * 判定手指是否触摸到了组件 , 是否在组件区域范围内 
     * @hide
     */
    protected boolean isTransformedTouchPointInView(float x, float y, View child,
            PointF outLocalPoint) {
        // 获取当前坐标 
        final float[] point = getTempPoint();
        point[0] = x;
        point[1] = y;
        transformPointToViewLocal(point, child);
        final boolean isInView = child.pointInView(point[0], point[1]);
        if (isInView && outLocalPoint != null) {
            outLocalPoint.set(point[0], point[1]);
        }
        return isInView;
    }

    /**
     * Gets the touch target for specified child view.
     * Returns null if not found.
     * 
     */
    private TouchTarget getTouchTarget(@NonNull View child) {
    	// 判断 mFirstTouchTarget 中的 child 字段 , 是否是当前遍历的 子组件 View 
    	// 如果是 , 则返回该 TouchTarget 
    	// 如果不是 , 则返回空
        for (TouchTarget target = mFirstTouchTarget; target != null; target = target.next) {
            if (target.child == child) {
                return target;
            }
        }
        return null;
    }


    /**
     * 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.
     * 该方法是正式分发触摸事件的方法 
     * 注意参数中传入了当前正在被遍历的 child 子组件 
     */
    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) {
                	// 被遍历的 child 子组件为空 
                	// 调用父类的分发方法 
                    handled = super.dispatchTouchEvent(event);
                } else {
                	// 被遍历的 child 子组件不为空 
                    final float offsetX = mScrollX - child.mLeft;
                    final float offsetY = mScrollY - child.mTop;
                    event.offsetLocation(offsetX, offsetY);

					// 子组件分发触摸事件 
					// 此处调用的是 View 组件的 dispatchTouchEvent 方法 ; 
                    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;
    }

    /**
     * Adds a touch target for specified child to the beginning of the list.
     * Assumes the target child is not already present.
     */
    private TouchTarget addTouchTarget(@NonNull View child, int pointerIdBits) {
        final TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
        target.next = mFirstTouchTarget;
        mFirstTouchTarget = target;
        return target;
    }

    @Override
    public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
    	// 设置父容器是否要拦截子组件的触摸事件

        if (disallowIntercept == ((mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0)) {
            // We're already in this state, assume our ancestors are too
            return;
        }

        if (disallowIntercept) {
            mGroupFlags |= FLAG_DISALLOW_INTERCEPT;
        } else {
            mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;
        }

        // Pass it up to our parent
        if (mParent != null) {
            mParent.requestDisallowInterceptTouchEvent(disallowIntercept);
        }
    }

}





五、View 事件分发相关源码



public class View implements Drawable.Callback, KeyEvent.Callback,
        AccessibilityEventSource {
    /**
     * Pass the touch screen motion event down to the target view, or this
     * view if it is the target.
     *
     * @param event The motion event to be dispatched.
     * @return True if the event was handled by the view, false otherwise.
     */
    public boolean dispatchTouchEvent(MotionEvent event) {
    	// 无障碍调用 , 辅助功能 
        // If the event should be handled by accessibility focus first.
        if (event.isTargetAccessibilityFocus()) {
            // We don't have focus or no virtual descendant has it, do not handle the event.
            if (!isAccessibilityFocusedViewOrHost()) {
                return false;
            }
            // We have focus and got the event, then use normal event dispatch.
            event.setTargetAccessibilityFocus(false);
        }

		// 返回结果 
        boolean result = false;

        if (mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
        }

		// 判定手指的动作 
        final int actionMasked = event.getActionMasked();
        if (actionMasked == MotionEvent.ACTION_DOWN) {
            // Defensive cleanup for new gesture
            stopNestedScroll();
        }

        if (onFilterTouchEventForSecurity(event)) {
            if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
                result = true;
            }
            //noinspection SimplifiableIfStatement
            // 设置的 触摸监听器 就是封装在该对象中 
            ListenerInfo li = mListenerInfo;
            // 判断该组件是否被用户设置了 触摸监听器 OnTouchListener
            if (li != null && li.mOnTouchListener != null
                    && (mViewFlags & ENABLED_MASK) == ENABLED
                    // 执行被用户设置的 触摸监听器 OnTouchListener
                    && li.mOnTouchListener.onTouch(this, event)) {
                // 如果用户设置的 触摸监听器 OnTouchListener 触摸方法返回 true
                // 此时该分发方法的返回值就是 true 
                result = true;
            }

			// 如果上面为 true ( 触摸监听器的触摸事件处理返回 true ) , 就会阻断该分支的命中 , 该分支不执行了 
			// 也就不会调用 View 组件自己的 onTouchEvent 方法 
			// 因此 , 如果用户的 触摸监听器 OnTouchListener 返回 true 
			// 则 用户的 点击监听器 OnClickListener 会被屏蔽掉 
			// 如果同时设置了 点击监听器 OnClickListener 和 触摸监听器 OnTouchListener 
			// 触摸监听器 OnTouchListener 返回 false , 点击监听器 OnClickListener 才能被调用到 
            if (!result && onTouchEvent(event)) {
                result = true;
            }
        }

        if (!result && mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
        }

        // Clean up after nested scrolls if this is the end of a gesture;
        // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
        // of the gesture.
        if (actionMasked == MotionEvent.ACTION_UP ||
                actionMasked == MotionEvent.ACTION_CANCEL ||
                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
            stopNestedScroll();
        }

        return result;
    }

    /**
     * Implement this method to handle touch screen motion events.
     * <p>
     * If this method is used to detect click actions, it is recommended that
     * the actions be performed by implementing and calling
     * {@link #performClick()}. This will ensure consistent system behavior,
     * including:
     * <ul>
     * <li>obeying click sound preferences
     * <li>dispatching OnClickListener calls
     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
     * accessibility features are enabled
     * </ul>
     *
     * @param event The motion event.
     * @return True if the event was handled, false otherwise.
     */
    public boolean onTouchEvent(MotionEvent event) {
        final float x = event.getX();
        final float y = event.getY();
        final int viewFlags = mViewFlags;
        final int action = event.getAction();

        final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE
                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;

        if ((viewFlags & ENABLED_MASK) == DISABLED) {
            if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
                setPressed(false);
            }
            mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
            // A disabled view that is clickable still consumes the touch
            // events, it just doesn't respond to them.
            return clickable;
        }
        if (mTouchDelegate != null) {
            if (mTouchDelegate.onTouchEvent(event)) {
                return true;
            }
        }

        if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
            switch (action) {
                case MotionEvent.ACTION_UP:
                	// 点击事件 Click 是 按下 + 抬起 事件 
                	// 如果要判定点击 , 需要同时有 MotionEvent.ACTION_DOWN + MotionEvent.ACTION_UP 事件 
                	
                    mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
                    if ((viewFlags & TOOLTIP) == TOOLTIP) {
                        handleTooltipUp();
                    }
                    if (!clickable) {
                        removeTapCallback();
                        removeLongPressCallback();
                        mInContextButtonPress = false;
                        mHasPerformedLongPress = false;
                        mIgnoreNextUpEvent = false;
                        break;
                    }
                    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)) {
                                    performClickInternal();
                                }
                            }
                        }

                        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:
                    if (event.getSource() == InputDevice.SOURCE_TOUCHSCREEN) {
                        mPrivateFlags3 |= PFLAG3_FINGER_DOWN;
                    }
                    mHasPerformedLongPress = false;

                    if (!clickable) {
                        checkForLongClick(0, x, y);
                        break;
                    }

                    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:
                    if (clickable) {
                        setPressed(false);
                    }
                    removeTapCallback();
                    removeLongPressCallback();
                    mInContextButtonPress = false;
                    mHasPerformedLongPress = false;
                    mIgnoreNextUpEvent = false;
                    mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
                    break;

                case MotionEvent.ACTION_MOVE:
                    if (clickable) {
                        drawableHotspotChanged(x, y);
                    }

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

            return true;
        }

        return false;
    }

    /**
     * Entry point for {@link #performClick()} - other methods on View should call it instead of
     * {@code performClick()} directly to make sure the autofill manager is notified when
     * necessary (as subclasses could extend {@code performClick()} without calling the parent's
     * method).
     */
    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();
    }

    /**
     * Call this view's OnClickListener, if it is defined.  Performs all normal
     * actions associated with clicking: reporting accessibility event, playing
     * a sound, etc.
     *
     * @return True there was an assigned OnClickListener that was called, false
     *         otherwise is returned.
     */
    // NOTE: other methods on View should not call this method directly, but performClickInternal()
    // instead, to guarantee that the autofill manager is notified when necessary (as subclasses
    // could extend this method without calling super.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 (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;
    }

}

源码路径 : /frameworks/base/core/java/android/view/View.java

这篇关于【Android 事件分发】事件分发源码分析 ( ViewGroup 事件传递机制 六 )的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!