android事件分发机制

19 篇文章 0 订阅
8 篇文章 0 订阅

基础知识

  1. MotionEvent
事件简介
ACTION_DOWN按下
ACTION_MOVE移动
ACTION_UP抬起
ACTION_CANCEL事件被上层拦截时触发
  1. 事件分发、拦截与消费
类型相关方法ActivityViewGroupView
事件分发dispatchTouchEvent☑️☑️☑️
事件拦截onInterceptTouchEvent✖️☑️✖️
事件消费onTouchEvent☑️✖️☑️

分发流程

分发流程

源码分析

在上述分发过程中,ViewGroup和View的dispatchTouchEvent是关键步骤,此处仅拿这两处源码来进行详细分析

  1. ViewGroup.dispatchTouchEvent
public boolean dispatchTouchEvent(MotionEvent ev) {
        ...
        //安全检查
        if (onFilterTouchEventForSecurity(ev)) {
            final int action = ev.getAction();
            final int actionMasked = action & MotionEvent.ACTION_MASK;

            // Handle an initial down.
            if (actionMasked == MotionEvent.ACTION_DOWN) {
                //按下时,清除历史状态,一次完整的事件重新开始了
                cancelAndClearTouchTargets(ev);
                resetTouchState();
            }

            // Check for interception.
            final boolean intercepted;
            if (actionMasked == MotionEvent.ACTION_DOWN
                    || mFirstTouchTarget != null) {
                //disallowIntercept变量是是否使拦截失效的标识
                final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
                if (!disallowIntercept) {
                    //拦截未失效,判断拦截
                    intercepted = onInterceptTouchEvent(ev);
                    ev.setAction(action); // restore action in case it was changed
                } else {
                    //拦截失效,直接不拦截
                    intercepted = false;
                }
            } else {
                // There are no touch targets and this action is not an initial down
                // so this view group continues to intercept touches.
                intercepted = true;
            }

            final boolean canceled = resetCancelNextUpFlag(this)
                    || actionMasked == MotionEvent.ACTION_CANCEL;
            if (!canceled && !intercepted) {

                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;

                    final int childrenCount = mChildrenCount;
                    if (newTouchTarget == null && childrenCount != 0) {
                        final float x = ev.getX(actionIndex);
                        final float y = ev.getY(actionIndex);
                        //对子组件按照层级进行排序
                        final ArrayList<View> preorderedList = buildTouchDispatchChildList();
                        final boolean customOrder = preorderedList == null
                                && isChildrenDrawingOrderEnabled();
                        final View[] children = mChildren;
                        
                        //遍历子组件,从最外层开始遍历
                        for (int i = childrenCount - 1; i >= 0; i--) {
                            final int childIndex = getAndVerifyPreorderedIndex(
                                    childrenCount, i, customOrder);
                            final View child = getAndVerifyPreorderedView(
                                    preorderedList, children, childIndex);
                        

                            //为 newTouchTarget 赋值
                            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);
                            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();
                                
                                newTouchTarget = addTouchTarget(child, idBitsToAssign);
                                alreadyDispatchedToNewTouchTarget = true;
                                break;
                            }
                            ev.setTargetAccessibilityFocus(false);
                        }
                        if (preorderedList != null) preorderedList.clear();
                    }

                }
            }

            // Dispatch to touch targets.
            if (mFirstTouchTarget == null) {
                // 如果未找到对应的子组件,则调用父类View的dispatchTouchEvent,进行处理
                handled = dispatchTransformedTouchEvent(ev, canceled, null,
                        TouchTarget.ALL_POINTER_IDS);
            } else {
                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;
                        //找到了对应的子组件,则调用子组件的 dispatchTouchEvent,进行处理
                        if (dispatchTransformedTouchEvent(ev, cancelChild,
                                target.child, target.pointerIdBits)) {
                            handled = true;
                        }
                    }
                    predecessor = target;
                    target = next;
                }
            }
        }
        return handled;
    }
  1. View.dispatchTouchEvent
public boolean dispatchTouchEvent(MotionEvent event) {
        ...
        //过滤事件安全,正常触摸为true
        if (onFilterTouchEventForSecurity(event)) {
            
            //ListenerInfo是在应用层中setOnTouchListener中初始化的
            ListenerInfo li = mListenerInfo;
            if (li != null && li.mOnTouchListener != null
                    //判断按钮能够点击
                    && (mViewFlags & ENABLED_MASK) == ENABLED
                    //即调用应用层实现的 onTouchListener
                    && li.mOnTouchListener.onTouch(this, event)) {
                //mOnTouchListener.onTouch为true时,返回true,事件被消费
                result = true;
            }

            if (!result && onTouchEvent(event)) {
                //如果result为false即未设置onTouchListener,则在onTouchEvent(event)中处理onClickListener,如果设置了点击监听,则仍然返回true,事件被消费
                result = true;
            }
        }

        ...

        return result;
    }
  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值