触摸事件来源的大致流程:
手指触摸屏幕时,即产生了触摸信息。这个触摸信息由屏幕这个硬件产生,被系统底层驱动获取,交给Android的输入系统服务:InputManagerService,也就是IMS
IMS会对这个触摸信息进行处理,经过WMS找到要分发的window,随后发送给对应的viewRootImpl。因此发送触摸信息的并非WMS,WMS提供的是window的相关信息。
当viewRootImpl接收到触摸信息时,也正是应用程序进程事件分发的开始。
事件分发:
DecorView -> Activity -> PhoneWindow -> DecorView
当屏幕被触摸input系统事件从Native层分发Framework层的InputEventReceiver.dispachInputEvent()调用了
android的view管理是以window为单位的,每一个window对应一个view树。Window机制不只管理着view的显示,也负责view的事件分发。关于window的本质,能够阅读笔者的另外一篇文章window机制。研究事件分发的来源,须要从window机制入手。布局
因此,首先要了解一个概念:view树,即viewRootImpl。
每一棵view树都有一个根,叫作ViewRootImpl ,他负责管理这整一棵view树的绘制、事件分发等。因此能够说,事件分发是从viewRootImpl开始的。
应用界面通常会有多个view树,activity布局就是一个view树、其余应用的悬浮窗也是一个view树、dialog界面也是一个view树、使用windowManager添加的view也是一个view树等等。最简单的view树能够只有一个view。
android中view的绘制和事件分发,都是以view树为单位。每一棵view树,则为一个window 。系统服务WindowManagerService,管理界面的显示就是以window为单位,也能够说是以view树为单位。而view树是由viewRootImpl来负责管理的,因此能够说,wms(WindowManagerService的简写)管理的是viewRootImpl。
对上图作个简单解释。
了解window机制的一个重要缘由是:事件分发并非由Activity驱动的,而是由系统服务驱动viewRootImpl来进行分
1、viewRootImpl会直接调用管理的view的 dispatchTouchEvent 方法,根据具体的view的类型,调用具体的方法。
2、view树的根view多是一个view,也多是一个viewGroup,view会直接处理事件,而viewGroup则会进行分发。
3、DecorView重写了 dispatchTouchEvent 方法,会先判断是否存在callBack,优先调用callBack的方法,也就是把事件传递给了Activity。
4、其余的viewGroup子类会根据自身的逻辑进行事件分发。
所以,触摸事件必定是从Activity开始的吗?不是,Activity只是其中的一种状况,只有Activity本身负责的那一棵view树,才必定会到达activity,而其余的window,则不会通过Activity。触摸事件是从viewRootImpl开始,而不是Activity。
Activity的这个方法从哪儿调用的呢?
Activity 的dispatchTouchEvent()事件:
/**
* Called to process touch screen events. You can override this to
* intercept all touch screen events before they are dispatched to the
* window. Be sure to call this implementation for touch screen events
* that should be handled normally.
*
* @param ev The touch screen event.
*
* @return boolean Return true if this event was consumed.
*/
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
onUserInteraction();
}
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
}
DecorView会调用superDispatchTouchEvent方法:
public boolean superDispatchTouchEvent(MotionEvent event){
return super.dispatchTouchEvent(event);
}
因为DecorView是一个FrameLayout,它最终还是调用了我们熟悉的ViewGroup的dispatchTouchEvent()
所谓的事件分发,本质上就是一个递归函数的调用,这个递归函数就是dispatchTouchEvent,至于onIntercepterTouchEvent,onTouchEvent,OnTouchListener,onClickListener…balabala都是在这个递归函数里面的操作而已,最核心,最骨干的还是dispatchTouchEvent。
事件分发的一个原则:一个view消费了某一个触点的down事件后,该触点事件序列的后续事件,都由该view消费 。
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
}
//如果事件以无障碍焦点的View为目标,并且此View就是那个无障碍焦点View则开始
//正常事件分发。
// 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;
/**
* 第一步:对于ACTION_DOWN进行处理(Handle an initial down)
* 因为ACTION_DOWN是一系列事件的开端,当是ACTION_DOWN时进行一些初始化操作.
* 从源码的注释也可以看出来:清除以往的Touch状态(state)开始新的手势(gesture)
* cancelAndClearTouchTargets(ev)中有一个非常重要的操作:
* 将mFirstTouchTarget设置为null!!!!
* 随后在resetTouchState()中重置Touch状态标识
**/
// 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)
* 在哪些情况下会调用该代码呢?有如下几种情况
* 1 处理ACTION_DOWN事件
* 2 当ACTION_DOWN事件被子View消费后处理ACTION_MOVE和ACTION_UP时
* 会调用该代码。因为此时mFirstTouchTarget!=null。所以此时ViewGroup
* 是有机会拦截ACTION_MOVE和ACTION_UP的,但是我们也可以调用方法:
* requestDisallowInterceptTouchEvent来禁止ViewGroup的事件拦截.
* 如果子View没有消费Touch事件,那么那么当后续的ACTION_MOVE和ACTION_UP
* 到来时是不会调用到本处代码的.
*
* 在dispatchTouchEvent(MotionEventev)这一大段代码中
* 使用变量intercepted来标记ViewGroup是否拦截Touch事件的传递.
* 该变量在后续代码中起着很重要的作用.
*
* 从此处if(actionMasked == MotionEvent.ACTION_DOWN || mFirstTouchTarget != null)及其内部代码可知:
* 当ViewGroup决定拦截事件后,那么后续的点击事件将会默认交给它处理,不再调用
* onInterceptTouchEvent()判断是否需要拦截.
* 这个是为什么?
* 因为在处理ACTION_DOWN时如果Touch事件被子View消费,那么mFirstTouchTarget不为空;
* 反之,如果Touch事件没有被子View消费,那么mFirstTouchTarget为空,即此时Touch由当前
* 的ViewGroup拦截。此时当ACTION_MOVE和ACTION_UP来到时,不再满足:
* if (actionMasked == MotionEvent.ACTION_DOWN || mFirstTouchTarget != null)
* 当然也就无法调用其内部的onInterceptTouchEvent()。
* 通俗地说:一旦ViewGroup拦截了ACTION_DOWN事件由自身的onTouchEvent()处理,那么
* 对于后续的ACTION_MOVE和ACTION_UP而言ViewGroup不再调用onInterceptTouchEvent()
* 判断是否拦截.
*
* 这里有个东西需要注意:FLAG_DISALLOW_INTERCEPT
* 在子View中调用requestDisallowInterceptTouchEvent()后造成disallowIntercept为true
* 即禁止拦截.于是不满足if(!disallowIntercept)所以也就调用不到该if内的onInterceptTouchEvent()
* 自然就没有办法拦截了.
* 但是requestDisallowInterceptTouchEvent()对于ACTION_DOWN是无效的.
* 因为对于ACTION_DOWN会调用 cancelAndClearTouchTargets(ev)和resetTouchState();
* 对FLAG_DISALLOW_INTERCEPT等状态值复原重置(参考上面的代码)
*
* 举两种情况说明:
* 1 当处理ACTION_DOWN时当然会满足
* if (actionMasked == MotionEvent.ACTION_DOWN || mFirstTouchTarget != null)
* 对于ACTION_DOWN子View有两种处理结果
* 1.1 消耗了Touch事件,那么mFirstTouchTarget不为null.
* 所以处理后续的ACTION_MOVE和ACTION_UP时依然满足该if判断
* 1.2 没有消耗Touch事件.mFirstTouchTarget=null.不满足该if.
* 所以后续的ACTION_MOVE和ACTION_UP由ViewGroup处理,此时再讨论什么拦截也就没有意义了.
* 同样的道理当子View消费了ACTION_DOWN后当处理ACTION_MOVE的时候ViewGroup拦截了该事件
* 那么当ACTION_UP随之到来时由于mFirstTouchTarget=null所以不会再调用该段代码,自然也就
* 不会调用onInterceptTouchEvent()判断是否拦截了.这点在上面的注释也有提及
* 2 当出现1.1的情况时满足该if判断.
* 如果在子View中调用了requestDisallowInterceptTouchEvent()那么就禁止拦截
* 即disallowIntercept=true.所以不满足if (!disallowIntercept)当然也就调用不到
* onInterceptTouchEvent(ev)了,而是执行else{ intercepted = false;}
* 也就是说ViewGroup无法拦截Touch了.
*/
// Check for interception.
final boolean intercepted;
// 事件为ACTION_DOWN或者mFirstTouchTarget不为null(即已经找到能够接收touch事件的目标组件)时if成立
if (actionMasked == MotionEvent.ACTION_DOWN
|| mFirstTouchTarget != null) {
//判断disallowIntercept(禁止拦截)标志位,可以理解为一个是否允许ViewGroup拦截的开关
//因为在其他地方可能调用了requestDisallowInterceptTouchEvent()设置mGroupFlags 改变该值.
//对于此方法的作用其实看requestDisallowInterceptTouchEvent()这个方法名就可明白了
//disallowIntercept 默认值为FALSE
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
//当禁止拦截为false时(即disallowIntercept为false)调用onInterceptTouchEvent(ev)方法
if (!disallowIntercept) {
//既然disallowIntercept为false那么就调用onInterceptTouchEvent()方法将结果赋值给intercepted
//常说事件传递中的流程是:dispatchTouchEvent->onInterceptTouchEvent->onTouchEvent
//其实在这就是一个体现,在dispatchTouchEvent()中调用了onInterceptTouchEvent()
intercepted = onInterceptTouchEvent(ev);
ev.setAction(action); // restore action in case it was changed
} else {
//禁止拦截的FLAG为ture说明没有必要去执行是否需要拦截了能够顺利通过,所以设置拦截变量为false
//即当禁止拦截为true时(即disallowIntercept为true)设置intercepted = false
//父view无法拦截事件
intercepted = false;
}
} else {
//当事件不是ACTION_DOWN并且mFirstTouchTarget为null(即没有Touch的目标组件)时
//设置 intercepted = true表示ViewGroup执行Touch事件拦截的操作。
// 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);
}
/**
* 第三步:检查cancel(Check for cancelation)
*
*/
// Check for cancelation.
final boolean canceled = resetCancelNextUpFlag(this)
|| actionMasked == MotionEvent.ACTION_CANCEL;
// Update list of touch targets for pointer down, if needed.
final boolean isMouseEvent = ev.getSource() == InputDevice.SOURCE_MOUSE;
/**
* 第四步:事件分发(Update list of touch targets for pointer down, if needed)
*/
final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0
&& !isMouseEvent;
TouchTarget newTouchTarget = null;
boolean alreadyDispatchedToNewTouchTarget = false;
//不是ACTION_CANCEL并且ViewGroup的拦截标志位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;
//处理ACTION_DOWN事件.这个环节比较繁琐
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);
final int childrenCount = mChildrenCount;
// 依据Touch坐标寻找子View来接收Touch事件
if (newTouchTarget == null && childrenCount != 0) {
final float x =
isMouseEvent ? ev.getXCursorPosition() : ev.getX(actionIndex);
final float y =
isMouseEvent ? ev.getYCursorPosition() : ev.getY(actionIndex);
// Find a child that can receive the event.
// Scan children from front to back.
final ArrayList<View> preorderedList = buildTouchDispatchChildList();
final boolean customOrder = preorderedList == null
&& isChildrenDrawingOrderEnabled();
final View[] children = mChildren;
// 遍历子View判断哪个子View接受Touch事件
for (int i = childrenCount - 1; i >= 0; i--) {
final int childIndex = getAndVerifyPreorderedIndex(
childrenCount, i, customOrder);
final View child = getAndVerifyPreorderedView(
preorderedList, children, childIndex);
if (!child.canReceivePointerEvents()
|| !isTransformedTouchPointInView(x, y, child, null)) {
continue;
}
newTouchTarget = getTouchTarget(child);
if (newTouchTarget != null) {
// 找到接收Touch事件的子View!!!!!!!即为newTouchTarget.
// 既然已经找到了,所以执行break跳出for循环
// 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不满足,当然也不会执行break语句.
* 于是代码会执行到这里来.
*
*
* 调用方法dispatchTransformedTouchEvent()将Touch事件传递给子View做
* 递归处理(也就是遍历该子View的View树)
* 该方法很重要,看一下源码中关于该方法的描述:
* 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.
* 将Touch事件传递给特定的子View.
* 该方法十分重要!!!!!!!!!!!!!!!!!
* 在该方法中为一个递归调用,会递归调用dispatchTouchEvent()方法!!!!!!!!!!
* 在dispatchTouchEvent()中:
* 如果子View为ViewGroup并且Touch没有被拦截那么递归调用dispatchTouchEvent()
* 如果子View为View那么就会调用其onTouchEvent(),这个不再赘述.
*
*
* 该方法返回true则表示子View消费掉该事件,同时进入该if判断.
* 满足if语句后重要的操作有:
* 1 给newTouchTarget赋值
* 2 给alreadyDispatchedToNewTouchTarget赋值为true.
* 看这个比较长的英语名字也可知其含义:已经将Touch派发给新的TouchTarget
* 3 执行break.
* 因为该for循环遍历子View判断哪个子View接受Touch事件,既然已经找到了
* 那么就跳出该for循环.
* 4 注意:
* 如果dispatchTransformedTouchEvent()返回false即子View的onTouchEvent返回false
* (即Touch事件未被消费)那么就不满足该if条件.所以也就无法执行addTouchTarget().
* 在此简单说一下addTouchTarget()中涉及到的ViewGroup的一个内部类TouchTarget——它是一个事件链.
* 该处的mFirstTouchTarget就是一个TouchTarget.它保存了可以消耗Touch事件的View.
* 在该处,如果dispatchTransformedTouchEvent()返回true即子View的onTouchEvent返回true则说明
* 该View消耗了Touch事件,那么将该View加入到事件链中!!!!!!!!!!!!!!!
* 尤其注意:
* 这个操作是在处理ACTION_DOWN的代码块里进行的.即是在:
* if (actionMasked == MotionEvent.ACTION_DOWN||
* (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN) ||
* actionMasked == MotionEvent.ACTION_HOVER_MOVE)
* 这个大的if判断中处理的.
* 当处理ACTION_MOVE事件和ACTION_UP事件的时候是不会进入这个if判断的!!!!!
* 而是直接从去判断mFirstTouchTarget!!!!!!!!!!!!!!!!
* 所以如果一个View不处理ACTION_DOWN那么该,那么该View是不会保存在mFirstTouchTarget
* 中的,也就无法继续处理ACTION_MOVE事件和ACTION_UP事件!!!!!!!!!!即若该View不消耗
* ACTION_DOWN事件那么系统是不会讲ACTION_MOVE和ACTION_UP事件传给给该View的
* 5 注意:
* 如果dispatchTransformedTouchEvent()返回true即子View
* 的onTouchEvent返回true(即Touch事件被消费)那么就满足该if条件.
* 从而mFirstTouchTarget不为null!!!!!!!!!!!!!!!!!!!
* 6 小结:
* 对于此处ACTION_DOWN的处理具体体现在dispatchTransformedTouchEvent()
* 该方法返回boolean,如下:
* true---->事件被消费----->mFirstTouchTarget!=null
* false--->事件未被消费--->mFirstTouchTarget==null
* 因为在dispatchTransformedTouchEvent()会调用递归调用dispatchTouchEvent()和onTouchEvent()
* 所以dispatchTransformedTouchEvent()的返回值实际上是由onTouchEvent()决定的.
*
* 简单地说onTouchEvent()是否消费了Touch事件(true or false)的返回值决定了
* dispatchTransformedTouchEvent()的返回值!!!!从而决定了mFirstTouchTarget是否为null!!!!!!
* 从而进一步决定了ViewGroup是否处理Touch事件.这一点在下面的代码中很有体现.
*/
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();
//调用addTouchTarget()将child添加到mFirstTouchTarget链表的表头
//注意在addTouchTarget()方法内部会对mFirstTouchTarget操作,使其不为null
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();
}
/**
* 该if条件表示:
* 经过前面的for循环没有找到子View接收Touch事件并且之前的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指向了最初的TouchTarget
newTouchTarget = newTouchTarget.next;
}
newTouchTarget.pointerIdBits |= idBitsToAssign;
}
}
}
/**
* 经过上面对于ACTION_DOWN的处理后mFirstTouchTarget有两种情况:
* (当然如果不是ACTION_DOWN就不会经过上面较繁琐的流程而是从此处开始执行,比如ACTION_MOVE和ACTION_UP)
*
* 情况1 mFirstTouchTarget为null
* 即没有找到能够消费touch事件的子组件或者是touch事件被拦截了
* 情况2 mFirstTouchTarget不为null
* 即找到了能够消费touch事件的子组件则后续的touch事件都可以传递到子View
* 这两种情况的详细分析见下.
*
* 这两种情况下都会去调用方法:
* dispatchTransformedTouchEvent(MotionEvent event,boolean cancel,View child,int desiredPointerIdBits)
* 我们重点关注该方法的第三个参数View child.
* 详情请参加下面dispatchTransformedTouchEvent()源码分析
* 在该源码中解释了:
* 为什么子view对于Touch事件处理返回true那么其上层的ViewGroup就无法处理Touch事件了!!!!!!!!!
* 为什么子view对于Touch事件处理返回false那么其上层的ViewGroup才可以处理Touch事件!!!!!!!!!!
*
*/
// 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 {
/**
* 情况2:mFirstTouchTarget不为null
* 即找到了可以消费Touch事件的子View且后续Touch事件可以传递到该子View
* 在源码中的注释为:
* Dispatch to touch targets, excluding the new touch target if we already dispatched to it.
* Cancel touch targets if necessary.
*/
// 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) {
//如果前面利用ACTION_DOWN事件寻找符合接收条件的子组件的同时消费掉了ACTION_DOWN事件
//那么这里为handled赋值为true
handled = true;
} else {
//对于非ACTION_DOWN事件继续传递给目标子组件进行处理
//依然是递归调用dispatchTransformedTouchEvent()
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;
}
}
/**
* 处理ACTION_UP和ACTION_CANCEL
* Update list of touch targets for pointer up or cancel, if needed.
* 在此主要的操作是还原状态
*/
// 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;
}
/**
* 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.
*/
/**
* 在dispatchTouchEvent()中会调用dispatchTransformedTouchEvent()将事件分发给子View处理
*
* 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.
*
* 在此请着重注意第三个参数:View child
* 在dispatchTouchEvent()中多次调用dispatchTransformedTouchEvent(),但是有时候第三个参数为null,有时又不是.
* 那么这个参数是否为null有什么区别呢?
* 在如下dispatchTransformedTouchEvent()源码中可见多次对于child是否为null的判断,并且均做出如下类似的操作:
* if (child == null) {
* handled = super.dispatchTouchEvent(event);
* } else {
* handled = child.dispatchTouchEvent(event);
* }
* 这个代码是什么意思呢?
*
* 当child == null时会将Touch事件传递给该ViewGroup自身的dispatchTouchEvent()处理.
* 即super.dispatchTouchEvent(event)
* 正如源码中的注释描述的一样:
* If child is null, assumes the MotionEvent will be sent to this ViewGroup instead.
*
* 当child != null时会调用该子view(当然该view可能是一个View也可能是一个ViewGroup)的dispatchTouchEvent(event)处理.
* 即child.dispatchTouchEvent(event);
*
* 那么该child是否为null又是由什么决定的呢?
* 在dispatchTouchEvent()中已经知道了:
* 如果Touch事件被消耗掉那么child不为null
* 如果Touch事件未被消耗掉那么child为null
*
* 这就解释了:
* 为什么子view对于Touch事件处理返回true那么其上层的ViewGroup就无法处理Touch事件了!!!!!!!!!
* 为什么子view对于Touch事件处理返回false那么其上层的ViewGroup才可以处理Touch事件!!!!!!!!!!
*/
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) {
handled = super.dispatchTouchEvent(event);
} else {
final float offsetX = mScrollX - child.mLeft;
final float offsetY = mScrollY - child.mTop;
event.offsetLocation(offsetX, offsetY);
handled = child.dispatchTouchEvent(event);
event.offsetLocation(-offsetX, -offsetY);
}
return handled;
}
transformedEvent = MotionEvent.obtain(event);
} else {
transformedEvent = event.split(newPointerIdBits);
}
// Perform any necessary transformations and dispatch.
if (child == null) {
handled = super.dispatchTouchEvent(transformedEvent);
} else {
final float offsetX = mScrollX - child.mLeft;
final float offsetY = mScrollY - child.mTop;
transformedEvent.offsetLocation(offsetX, offsetY);
if (! child.hasIdentityMatrix()) {
transformedEvent.transform(child.getInverseMatrix());
}
handled = child.dispatchTouchEvent(transformedEvent);
}
// Done.
transformedEvent.recycle();
return handled;
}
/**
* 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) {
//判断当前事件是否能获得焦点,如果不能获得焦点或者不存在一个View,那我们就直接返回False跳出循环
// 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;
if (li != null && li.mOnTouchListener != null
&& (mViewFlags & ENABLED_MASK) == ENABLED
&& li.mOnTouchListener.onTouch(this, event)) {
result = true;
}
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;
}
负责对事件进行分发的方法主要有三个,分别是:
Down事件的分发决定了那个view要捕获事件,如果捕获了,后续的事件就直接分发给它,也就是说move up等事件的分发交给谁,取决于它们的起始事件Down由谁捕获。
//本源码来自 api 28,不同版本略有不同。
public boolean dispatchTouchEvent(MotionEvent ev) {
// 第一步:处理拦截
boolean intercepted;
// 注意这个条件,后者代表着有子view消费事件。后面会讲
if (actionMasked == MotionEvent.ACTION_DOWN || mFirstTouchTarget != null) {
// 子view调用了parent.requestDisallowInterceptTouchEvent干预父布局的拦截,不让它爸拦截它
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
if (!disallowIntercept) {
intercepted = onInterceptTouchEvent(ev);
ev.setAction(action);
} else {
intercepted = false;
}
} else {
//既不是DOWN事件,mFirstTouchTarget还是null,这种情况挺常见:如果ViewGroup的所有的子View都不消费 //事件,那么当ACTION_MOVE等非DOWN事件到来时,都被拦截了。
intercepted = true;
}
// 第二步,分发ACTION_DOWN
boolean handled = false;
boolean alreadyDispatchedToNewTouchTarget = false; //注意这个变量,会用到
// 不拦截才会分发它,如果拦截了,就不分发ACTION_DOWN了
if (!intercepted) {
//处理DOWN事件,捕获第一个被触摸的mFirstTouchTarget,mFirstTouchTarget很重要,
保存了消费了ACTION_DOWN事件的子view
if (ev.getAction == MotionEvent.ACTION_DOWN) {
//遍历所有子view(看源码知子View是按照Z轴排好序的)
for (int i = childrenCount - 1; i >= 0; i--) {
//子view如果:1.不包含事件坐标 2. 在动画 则跳过
if (!isTransformedTouchPointInView() || !canViewReceivePointerEvents()) {
continue;
}
//将事件传递给子view的坐标空间,并且判断该子view是否消费这个触摸事件(分发Down事件)
if (dispatchTransformedTouchEvent()) {
//将该view加入头节点,并且赋值给mFirstTouchTarget
newTouchTarget = addTouchTarget(child, idBitsToAssign);
alreadyDispatchedToNewTouchTarget = true;
break;
}
}
}
}
//第三步:分发非DOWN事件
//如果没有子view捕获ACTION_DOWN,则交给本ViewGroup处理这个事件。我们看到,这里并没有判断是否拦截,
//为什么呢?因为如果拦截的话,上面的代码不会执行,就会导致mFirstTouchTarget== null,于是就走下面第一 //个条件里的逻辑了
if (mFirstTouchTarget == null) {
super.dispatchTouchEvent(ev); //调用View的dispatchTouchEvent,也就是自己处理
} else {
//遍历touchTargets链表,依次分发事件
TouchTarget target = mFirstTouchTarget;
while (target != null) {
if (alreadyDispatchedToNewTouchTarget) {
handled = true
} else {
if (dispatchTransformedTouchEvent()) {
handled = true;
}
target = target.next;
}
}
}
//处理ACTION_UP和CANCEL,手指抬起来以后相关变量重置
if (ev.getAction == MotionEvent.ACTION_UP) {
reset();
}
}
return handled;
}
1、IMS从系统底层接收到事件以后,会从WMS中获取window信息,并将事件信息发送给对应的viewRootImpl
2、viewRootImpl接收到事件信息,封装成motionEvent对象后,发送给管理的view
3、iew会根据自身的类型,对事件进行分发仍是本身处理
4、顶层viewGroup通常是DecorView,DecorView会根据自身callBack的状况,选择调用callBack或者调用父类ViewGroup的方法
5、事件分发分两步,拦截和分发,其中分发有两种情况,Down事件和非Down事件,down事件是事件链的起点,决定了要不要消费事件,而且将消费的子View保存下来给后面使用。如果所有的子View都不消费down事件或者压根没有子View,会使得mFirstTouchTarget为null,后面的所有事件就不再分发给子view了,直接由本view group处理。当然这里的交给本人处理,实际上可能它也不消费,会继续往上传,最终“归”到Activity处理。
参考资料:
Android全面解析之Window机制
https://juejin.cn/post/6888688477714841608
Android事件分发机制一:事件是如何到达activity的?
https://www.shangmayuan.com/a/5709df5f4765468ebe0903ee.html
Android事件分发流程总结
https://blog.csdn.net/murongyeye/article/details/116136700
Input系统-事件处理全过程
你真的看懂Android事件分发了吗?
https://www.cnblogs.com/jymblog/p/12178527.html
Android事件分发详解(三)——ViewGroup的dispatchTouchEvent()源码学习
https://blog.csdn.net/lfdfhl/article/details/50707724
Android事件分发机制二:viewGroup与view对事件的处理
https://www.cnblogs.com/huan89/archive/2021/01/22/14315809.html