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

简介: 【Android 事件分发】事件分发源码分析 ( ViewGroup 事件传递机制 二 )

文章目录

Android 事件分发 系列文章目录

前言

一、获取触摸索引值

二、按照 Z 轴深度排序组件

三、ViewGroup 事件分发相关源码

前言

接上一篇博客 【Android 事件分发】事件分发源码分析 ( ViewGroup 事件传递机制 一 ) , 继续分析 ViewGroup 的事件分发机制后续代码 ;






一、获取触摸索引值


首先在 动作事件不是取消操作 , 且不拦截事件 , 的前提下 , 才能执行后续操作 , 判定代码如下 :


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


凡是涉及到 Accessibility 功能的 , 直接忽略 , 与当前分析的事件分发无关 ;


           

View childWithAccessibilityFocus = ev.isTargetAccessibilityFocus()
                        ? findChildWithAccessibilityFocus() : null;


再次判定是否是按下操作 ;


 

// 判断是否是按下操作 
                if (actionMasked == MotionEvent.ACTION_DOWN
                        || (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)
                        || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {


如果是按下操作 , 则获取触摸索引值 , 从 0 开始计数 ;


               

// 获取触摸索引值 
                    final int actionIndex = ev.getActionIndex(); // always 0 for down


ViewGroup | dispatchTouchEvent 方法相关源码 :


@UiThread
public abstract class ViewGroup extends View implements ViewParent, ViewManager {
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
  ...
    // 此处判定 , 是否拦截 
    // 假定不取消 , 也不拦截 
    // 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;
    // 判断是否是按下操作 
                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);
  ...
  }
}



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






二、按照 Z 轴深度排序组件


先计算 ViewGroup 父容器下面有多少个子 View 组件 ;


 

// 计算 ViewGroup 父容器下面有多少个子 View 组件 ; 
                    final int childrenCount = mChildrenCount;

如果子组件个数为 0 , 则不走下一段代码 , 如果子组件个数大于 0 , 则执行下一段代码 ; 说明下面的代码块中处理的是 ViewGroup 中子组件的事件分发功能 ;


在子组件个数不为 0 的情况下 , 继续向后执行 ;



获取手指触摸的 x, y 坐标值 ;


                 

// 获取单个手指的 x,y 坐标 
                        final float x = ev.getX(actionIndex);
                        final float y = ev.getY(actionIndex);


子组件排序 : 按照 Z 轴排列的层级 , 从上到下进行排序 , 控件会相互重叠 , Z 轴的排列次序上 , 顶层的组件优先获取到触摸事件 ;


             

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



ViewGroup | buildTouchDispatchChildList 方法是排序的核心方法 ;


获取当前所有组件的子组件的 Z 轴的深度 , 按照 Z 轴深度进行排序 , Z 轴方向上 , 对于事件传递 , 上面的组件优先级高于被覆盖的下面的组件优先级 ;


下面的代码是组件遍历排序的核心逻辑 :


   

// 下面的组件排序的核心逻辑 
        // 获取当前所有组件的子组件的 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);
        }



ViewGroup | dispatchTouchEvent / buildOrderedChildList 方法相关源码 :


@UiThread
public abstract class ViewGroup extends View implements ViewParent, ViewManager {
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
  ...
      // 计算 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;
  ...
  }
    /**
     * 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;
    }
}



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






三、ViewGroup 事件分发相关源码


ViewGroup 事件分发相关源码 : 下面的代码中 , 逐行注释分析了 ViewGroup 的 dispatchTouchEvent 事件分发操作 ;


@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;
    // 判断是否是按下操作 
                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;
  ... 
        return handled;
    }
    @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;
    }
}



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


目录
相关文章
|
开发框架 前端开发 Android开发
Flutter 与原生模块(Android 和 iOS)之间的通信机制,包括方法调用、事件传递等,分析了通信的必要性、主要方式、数据传递、性能优化及错误处理,并通过实际案例展示了其应用效果,展望了未来的发展趋势
本文深入探讨了 Flutter 与原生模块(Android 和 iOS)之间的通信机制,包括方法调用、事件传递等,分析了通信的必要性、主要方式、数据传递、性能优化及错误处理,并通过实际案例展示了其应用效果,展望了未来的发展趋势。这对于实现高效的跨平台移动应用开发具有重要指导意义。
1810 4
|
存储 安全 Android开发
探索Android与iOS的隐私保护机制
在数字化时代,移动设备已成为我们生活的一部分,而隐私安全是用户最为关注的问题之一。本文将深入探讨Android和iOS两大主流操作系统在隐私保护方面的策略和实现方式,分析它们各自的优势和不足,以及如何更好地保护用户的隐私。
|
消息中间件 存储 Java
Android消息处理机制(Handler+Looper+Message+MessageQueue)
Android消息处理机制(Handler+Looper+Message+MessageQueue)
411 2
|
消息中间件 Android开发
Android Handler的使用方式以及其机制的简单介绍
Handler 是 Android 中实现线程间通信的重要机制,可传递任意两线程数据。常用场景包括子线程向主线程(UI 线程)传递结果,以及主线程向子线程发送消息。其核心涉及四个类:Handler(发送/接收消息)、Message(消息载体)、MessageQueue(消息队列)和 Looper(消息循环泵)。基本流程为:Handler 发送 Message 至 MessageQueue,Looper 从队列中按 FIFO 取出并处理。
549 0
|
Linux Android开发 iOS开发
深入探索Android与iOS的多任务处理机制
在移动操作系统领域,Android和iOS各有千秋,尤其在多任务处理上展现出不同的设计理念和技术实现。本文将深入剖析两大平台在后台管理、资源分配及用户体验方面的策略差异,揭示它们如何平衡性能与电池寿命,为用户带来流畅而高效的操作体验。通过对比分析,我们不仅能够更好地理解各自系统的工作机制,还能为开发者优化应用提供参考。
|
算法 Linux 调度
深入探索安卓系统的多任务处理机制
【10月更文挑战第21天】 本文旨在为读者提供一个关于Android系统多任务处理机制的全面解析。我们将从Android操作系统的核心架构出发,探讨其如何管理多个应用程序的同时运行,包括进程调度、内存管理和电量优化等方面。通过深入分析,本文揭示了Android在处理多任务时所面临的挑战以及它如何通过创新的解决方案来提高用户体验和设备性能。
1182 1
|
消息中间件 存储 Java
Android面试高频知识点(2) 详解Android消息处理机制(Handler)
Android面试高频知识点(2) 详解Android消息处理机制(Handler)
|
消息中间件 存储 Java
Android消息处理机制(Handler+Looper+Message+MessageQueue)
Android消息处理机制(Handler+Looper+Message+MessageQueue)
720 2
|
消息中间件 存储 Java
Android面试高频知识点(2) 详解Android消息处理机制(Handler)
Android面试高频知识点(2) 详解Android消息处理机制(Handler)
613 1
|
存储 安全 数据安全/隐私保护
探索安卓与iOS的隐私保护机制####
【10月更文挑战第15天】 本文深入剖析了安卓和iOS两大操作系统在隐私保护方面的策略与技术实现,旨在揭示两者如何通过不同的技术手段来保障用户数据的安全与隐私。文章将逐一探讨各自的隐私控制功能、加密措施以及用户权限管理,为读者提供一个全面而深入的理解。 ####
1263 1

热门文章

最新文章