android分发机制---- 源码解析

android中分发机制在自定义的View中尤为重要,贯穿android Activity – ViewGroup – View的Event传递;

为了提高理解,我们分部阐述

1.android分发机制概述
2.图解
3.android源码

1.android分发机制
  • 在android中Event是自上而下分发的:Activity —-> ViewGroup —-> View
  • 涉及到3个方法:
    • dispatchTouchEvent—-事件的总调度,贯穿事件分发的主逻辑线
    • onInterceptTouchEvent—- 拦截方法,拦截事件决定后序的分发是否依然向下分发
    • onTouchEvent—- 事件Event真正的消费方法
  • 在android中,首先是从Activity进行分发,Activity通过dispatchTouchEvent分发到DecorView的dispatchTouchEvent中,这里的DecorView(Activity的根View)就是一个ViewGroup;在ViewGroup中进行事件分发,会有事件拦截onInterceptTouchEvent,onInterceptTouchEvent返回true,则事件由本层消费,返回false,继续向下分发;
  • 注意:
    • Activityh和View只有dispatchTouchEvent和onTouchEvent;
    • ViewGroup有dispatchTouchEvent,onInterceptTouchEvent,onTouchEvent

以上都是基本常识,下面来看android分发的图例;(图解的出现更加有利于对android分发机制的理解)

2.android分发机制图解

这里写图片描述
从图中可以看到android的分发就是一个一层一层嵌套的过程

Activity中dispatchTouchEvent分发到ViewGroup,ViewGroup中dispatchTouchEvent分发到View,View树一层一层的遍历分发,自上而下,然后父层dispatchTouchEvent通过接收下一层dispatchTouchEvent的返回来决定是否终结分发流程;

有一点拗口,其实可以这样理解:
android分发是自上而下分发,当然是在不拦截的情况下;如果拦截则交于本层消费;在不拦截的情况下,传递到最底层的View来消费,若底层不消费,则返回到父类的dispatchTouchEvent,由父类消费,同理,若父类没有消费,则继续向上传递,直到Activity,就是整个分发的顶层,默认处理;

3.源码解析
3.1首先来看Activity源码:
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
              //实现屏保功能
              //a. 该方法为空方法
              //b. 当此activity在栈顶时,触屏点击按home,back,menu键等都会触发此方法
            onUserInteraction();
        }
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }
  • 首先在MotionEvent.ACTION_DOWN的时候会有onUserInteraction();他是一个空方法;主要是实现屏保功能,当activity在栈顶时候,点击home/back/menu均会触发该方法;

  • 然后来看核心代码:getWindow().superDispatchTouchEvent(ev) ;提前剧透一下getWindow().superDispatchTouchEvent(ev)就是在调用ViewGroup的分发方法:dispatchTouchEvent(ev),如果ViewGroup中event被消费或者是被其子View消费掉(dispatchTouchEvent—>onTouchEvent),则Activity中dispatchTouchEvent返回true,事件分发结束;否则Activity调用onTouchEvent(ev),由Activity完成事件消费;

### getWindow()---- return  PhoneWindow
### PhoneWindow
    @Override
    public boolean superDispatchTouchEvent(MotionEvent event) {
        return mDecor.superDispatchTouchEvent(event);
    }
### DecorView
     public boolean superDispatchTouchEvent(MotionEvent event) {
        return super.dispatchTouchEvent(event);
     }

因为DecorView继承自ViewGroup,so这里的super.dispatchTouchEvent(event)就是ViewGroup的dispatchTouchEvent(event):

@Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
    ......
          //解析一:
          if (actionMasked == MotionEvent.ACTION_DOWN) {
                    //当开始一个新的触摸手势时,扔掉所有先前的状态
                    //框架可能已经删除了前一个阶段的UP或取消事件
                    //由于应用程序切换,ANR,或其他一些状态改变。
                    cancelAndClearTouchTargets(ev);
                    resetTouchState();
           }
          //解析二:
            final boolean intercepted;
            if (actionMasked == MotionEvent.ACTION_DOWN
                    || mFirstTouchTarget != null) {
                final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
                if (!disallowIntercept) {
                    intercepted = onInterceptTouchEvent(ev);
                    ev.setAction(action); // restore action in case it was changed
                } else {
                    intercepted = false;
                }
            } else {
                intercepted = true;
            }
    }
  • 解析一:
    • 在事件分发过程中首先通过 cancelAndClearTouchTargets(ev)resetTouchState()来cancel之前的状态和事件,
  • 解析二:
    • 在ViewGroup中处理事件拦截:
    • if (actionMasked == MotionEvent.ACTION_DOWN
      || mFirstTouchTarget != null)不成立

      事件拦截的标志位intercepted = true;事件直接拦截
      -if (actionMasked == MotionEvent.ACTION_DOWN
      || mFirstTouchTarget != null)成立

      继续看disallowIntercept,如果为false,则会返回
      intercepted = onInterceptTouchEvent(ev)
      为true,直接intercepted = true 拦截;

这里需要注意一下 intercepted = onInterceptTouchEvent(ev)就是ViewGroup的拦截事件方法;
其次,父 View 会为子View 创建一个 TouchTarget 实例加入链表中,链表的第一项为 mFirstTouchTarget。后续的 move 和 up 事件会直接交给该 View的dispatchTouchEvent。

在ViewGroup中拦截方法,之后姚根据拦截状态,进行继续的向下分发:
仍然是

    public boolean dispatchTouchEvent(MotionEvent ev) {
    ......
            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;
                }
            }
    }

    //核心代码
     private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
            View child, int desiredPointerIdBits) {
        final boolean handled;


        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;
        }
    ......

ViewGroup中代码比较多,所以仅粘贴关键代码,在拦截之后会遍历其子View,根据焦点和坐标定位点击的child,然后根据拦截状态intercepted来进行处理;

handled = child.dispatchTouchEvent(event);

这个handled就是在ViewGroup中返回下一层的分发结果,如果handled返回true则分发结束;如果返回false,则事件有ViewGroup来处理;
在这里dispatchTransformTouchEvent 完成了分发的最后过程:
1. 传入的 child 不为空,转化坐标为 child 的坐标系,调用 child.dispatchTouchEvent 向 child 分发事件
2. 传入的 child 为空,调用 super.dispatchTouchEvent 分发事件到 onTouchEvent 中
由于代码确实太多我们来简化模拟一段伪代码:

public boolean dispatchTouchEvent(MotionEvent e) {
    boolean handled = false;
    if (onInterceptTouchEvent(e)) {
        //如果拦截  则在ViewGroup中消费时间
        handled = onTouchEvent(e);
    } else {
        for (View view: childs) {
            //Event在子View的处理结果
            handled = view.dispatchTouchEvent(e);
            if (handled) {
                break;
            }
        }
        //子View没有消费event 返回false ViewGroup自行处理  
        //当然  如果ViewGroup仍然返回false则继续向上传递
        if (!handled) {
            handled = onTouchEvent(e);
        }
    }   
    return consumed;
}

我们继续看View的源码:

public boolean dispatchTouchEvent(MotionEvent event) {
        ......
        if (onFilterTouchEventForSecurity(event)) {
            if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
                result = true;
            }
            //noinspection SimplifiableIfStatement
            ListenerInfo li = mListenerInfo;
            if (li != null && li.mOnTouchListener != null
                    && (mViewFlags & ENABLED_MASK) == ENABLED
                    && li.mOnTouchListener.onTouch(this, event)) {
                result = true;
            }

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

这里需要注意一下在View的dispatchTouchEvent中, View 为 ENABLE 的状态并且有 mTouchListener,会先调用 onTouch。在 onTouch 返回 false 时才会继续调用 onTouchEvent,然后在onTouchEvent中调用performClick,返回true则事件消费,返回false则向上传递;

到这里,事件分发整个流程源码就结束了;由于代码太多,所以仅粘贴关键代码;
源码解析完之后,回头看图解就会豁然开朗;

夏日炎炎,会有遗漏,期待反馈;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值