1 什么是事件
这里的事件主要是指点击事件,因为Android设备同用户进行交互的主要方式就是触摸屏幕,包括点击,滑动等一系列的动作。这些动作都会产生一系列的MotionEvent对象,由屏幕驱动程序将触摸屏幕动作的相关信息(触摸的位置等)打包成这些对象,交由Android系统处理。这些对象,即为本文需要分析的事件。
一次正常的触摸动作一般以一个ACTION_DOWN事件开始,中间有若干个或零个ACTION_MOVE事件,以一个ACTION_UP事件结束。
2 什么是事件分发
事件分发的本质其实就是对MotionEvent对象的分发过程。当这些事件由底层交由Android系统后,系统需要把这个事件传递给一个具体的View进行处理,这个传递的过程,就是事件分发。
事件分发的过程中,有3个很重要的方法参与,分别为:dispatchTouchEvent()、onInterceptTouchEvent()和onTouchEvent(),这三个方法存在于View和ViewGroup类中,本文也将就这三个方法在View和ViewGroup中的具体源码来分析事件分发的具体流程。
3 事件分发流程
3.1 从Activity到ViewGroup
在讨论接下来的内容之前,我们需要把结论先放出来,带着结论去继续分析,帮助理解。
结论1.当一个MotionEvent由底层传给Android系统后,最先收到这个MotionEvent对象的是当前顶层的Activity。
因此,我们分析事件分发的入口,就是Activity这个类,更具体一些,是Activity.dispatchTouchEvent()方法,如下,
// Activity.java
/**
* 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() 默认是空方法 需要用户自行重写 一般用作屏幕保护功能
onUserInteraction();
}
// 若此处返回为true则直接返回 否则调用Activity的onTouchEvent方法处理事件
// 返回为true说明该事件已经由其child节点处理 不再需要父节点Activity处理
// 返回为false说明该事件在遍历了所有child节点后 还没有被处理 因此还需要继续调用父节点Activity的onTouchEvent方法处理事件
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
}
上述源码中,getWindow()方法返回的是一个Window类对象,Window.java是个抽象类,其唯一实现类是PhoneWindow.java从类名可以看出,Window类是对屏幕的抽象类,而PhoneWindow类则是手机屏幕的具体实现类,继续分析PhoneWindow.superDispatchTouchEvent()方法,如下,
// PhoneWindow.java
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
// PhoneWindow直接将MotionEvent对象交给mDecor处理
// 这个mDecor对象 是最顶层的View 我们平时在Activity中setContentView()方法 就是将View设置为mDecor的子View
return mDecor.superDispatchTouchEvent(event);
}
mDecor在Activity中的申明如下,
// PhoneWindow.java
// This is the top-level view of the window, containing the window decor.
// 从上述官方注释中也能看出mDecor就是最顶层的View
private DecorView mDecor;
// DecorView.superDispatchTouchEvent()
public boolean superDispatchTouchEvent(MotionEvent event) {
// 直接调用父类的dispatchTouchEvent()
return super.dispatchTouchEvent(event);
}
这个mDecor既然是顶层View,那么其本质也就是个View类,查看其源码可以看出,DecorView继承了FrameLayout,而FrameLayout又继承了ViewGroup,因此此处调用super.dispatchTouchEvent()方法,会将该事件传递到ViewGroup.dispatchTouchEvent()。
第一阶段的分析我们先到这,做个初步的总结,
1.MotionEvent对象最先传递给Activity分发,注意,是分发,并不是交给Activity处理。
2.Activity是否处理这个事件要看子节点们是否已经处理事件,只有子节点们返回未处理事件,Activity才会去处理该事件
3.Activity中有一个抽象类Window的对象mWindow,其唯一实现类为PhoneWindow,mWindow拥有最顶层View的对象mDecor。
4.整个事件分发过程其实是在一个树状的结构中进行的,其本质是因为Android布局的结构是树状的。如下图,
3.2 分发——从ViewGroup到View
这部分会是整个事件分发流程的重点和难点,同上一小节,在讨论接下来的内容时,先说一个个人理解,我觉得带着这个个人理解去剖析整个事件分发流程会更顺畅一些。
结论1.ViewGroup的职责是分发事件,View的职责是处理事件
结论2.当一个ViewGroup收到一个MotionEvent时,会优先考虑将其分发出去,而不是交给自己处理,即ViewGroup首先是一个ViewGroup。只有在其子View返回false表示不处理该事件时,ViewGroup才考虑自己作为View的职责,去处理事件。
继续分析ViewGroup.DispatchTouchEvent()方法
// ViewGroup
@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;
// 每次ACTION_DOWN事件都会走一遍如下流程 因为每个ACTION_DOWN事件都标志着一次触摸过程的开始
// 需要清除掉上一次触摸动作所记录下来的标志位
// 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);
// 此处会重置FLAG_DISALLOW_INTERCEPT这个FLAG的状态
resetTouchState();
}
// 所有的触摸事件都是以ACTION_DOWN事件开始
// mFirstTouchTarget在后面会指向成功处理该事件的子元素(如果存在)
// Check for interception.
final boolean intercepted;
// 当ACTION_DOWN事件传递到ViewGroup中时 下面代码块一定会执行
// 另外 当除了ACTION_DOWN事件传递到此处时 即便已经有子View处理了之前的事件 即mFirstTouchTarget != null
// 我们也可以通过onInterceptTouchEvent()方法进行拦截
if (actionMasked == MotionEvent.ACTION_DOWN
|| mFirstTouchTarget != null) {
// 此标志位提供给ViewGroup的子View来设置 可用于控制父ViewGroup是否拦截事件
// 子View可通过requestDisallowInterceptTouchEvent()方法来设置
// requestDisallowInterceptTouchEvent(true) 则父ViewGroup的disallowIntercept为true 即父ViewGroup不允许拦截事件
// requestDisallowInterceptTouchEvent(false) 则父ViewGroup的disallowIntercept为false 父ViewGroup是否拦截事件取决于父元素的onInterceptTouchEvent()方法返回值
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
if (!disallowIntercept) {
// onInterceptTouchEvent()默认返回false
// 默认ViewGroup不拦截事件
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.
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;
final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0
&& !isMouseEvent;
TouchTarget newTouchTarget = null;
boolean alreadyDispatchedToNewTouchTarget = 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) { // 1
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;
//
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;
// 遍历子节点
for (int i = childrenCount - 1; i >= 0; i--) { // 2
final int childIndex = getAndVerifyPreorderedIndex(
childrenCount, i, customOrder);
final View child = getAndVerifyPreorderedView(
preorderedList, children, childIndex);
// 如果View为INVISIBLE或者点击事件不在View范围内
// 表示当前Child View无法处理该事件 遍历下一个
if (!child.canReceivePointerEvents()
|| !isTransformedTouchPointInView(x, y, child, null)) {
continue;
}
// 找了了合适的Child View
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);
// 此处会去调用child的dispatchTouchEvent()
// 如果Child View的dispatchTouchEvent()返回true 即子View处理了该事件 一般为ACTION_DOWN事件 会执行下面的代码块
// 下面的代码块会为mFirstTouchTarget赋值 此后mFirstTouchTarget != null
if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) { // 3
// 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()会为mFirstTouchTarget赋值
newTouchTarget = addTouchTarget(child, idBitsToAssign);
// 标志位 指明该ACTION_DOWN事件已经被处理
alreadyDispatchedToNewTouchTarget = true;
// 跳出遍历子View的循环
break;
} // 3
// The accessibility focus didn't handle the event, so clear
// the flag and do a normal dispatch to all children.
ev.setTargetAccessibilityFocus(false);
} // 2
if (preorderedList != null) preorderedList.clear();
}
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;
}
} // 1
}
// 此处所有事件都可以走到这里 如果此时mFirstTouchTarget == null 说明没有子View可以处理这一事件
// Dispatch to touch targets.
if (mFirstTouchTarget == null) {
// 此处会调用super.dispatchTouchEvent ViewGroup的父类为View 即去调用View的dispatchTouchEvent()处理这个事件
// 验证了前面的结论2 即ViewGroup负责分发事件 View负责处理事件 只有在所有子View均无法处理该事件时 ViewGroup才会执行View的功能
// 下面的官方注释也说明了这一点
// No touch targets so treat this as an ordinary view.
handled = dispatchTransformedTouchEvent(ev, canceled, null,
TouchTarget.ALL_POINTER_IDS);
} else {
// 已经有子View处理了之前的ACTION_DOWN事件 需要将后续事件继续传递给该子View
// 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;
// 此处由于ACTION_DOWN事件也会继续走到这部分代码块 即便前面已经处理了该ACTION_DOWN事件 因此这个标志位alreadyDispatchedToNewTouchTarget
// 用于避免ACTION_DOWN事件被重复处理
if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
handled = true;
} else {
// 后续ACTION_MOVE和ACTION_UP事件会继续交给该子View
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);
}
return handled;
}
这部分代码很长,逻辑也很复杂,我们以一组正常的事件序列来走一遍上述逻辑。
一组正常的事件序列一般为:ACTION_DOWN --> ACTION_MOVE --> ... --> ACTION_MOVE --> ACTION_UP
1 ACTION_DOWN事件最先进入分发流程,且一定会调用ViewGroup的onInterceptTouchEvent()方法来判断是否拦截该事件。
2-1 拦截了ACTION_DOWN事件,导致不会走后续遍历子View寻找处理该ACTION_DOWN事件的子View流程,因此mFirstTouchTarget == null,ViewGroup想起来自己还是个View,调用自身的dispatchTouchEvent()方法处理该ACTION_DOWN事件。
2-2 未拦截ACTION_DOWN事件,进入遍历子View的循环中,寻找是否有合适的子View处理该事件。
2-2-1 找到了合适的子View处理该ACTION_DOWN事件,mFirstTouchTarget != null,并且标志位alreadyDispatchedToNewTouchTarget == true,后面不会再处理这个ACTION_DOWN事件。
2-2-2 未找到合适的子View处理该ACTION_DOWN事件,mFirstTouchTarget == null,同2-1,ViewGroup想起来自己还是个View,调用自身的dispatchTouchEvent()方法处理该ACTION_DOWN事件。
上面是第一个ACTION_DOWN事件可能的分发流程
3-1 由于2-1中拦截了ACTION_DOWN事件,导致了mFirstTouchTarget == null,因此无论onInterceptTouchEvent()方法是否拦截该事件,由于mFirstTouchTarget == null,都不会再走后续遍历所有子View寻找处理该ACTION_MOVE事件的子View循环,也就是说,后续事件再也不会分发给任何子View,ViewGroup又想起来自己是个View,调用自身的dispatchTouchEvent()方法处理该ACTION_DOWN事件。
3-2 由于2-2中未拦截ACTION_DOWN事件。
3-2-1 由于找到了合适的子View处理之前的ACTION_DOWN事件,所以mFirstTouchTarget != null,因此onInterceptTouchEvent()也会得到执行(我们可以通过重写这个方法来决定是否拦截ACTION_MOVE事件,外部拦截法就是通过这个方式实现)
3-2-2 此处如果走了2-2-2流程,同样mFirstTouchTarget == null,也会同3-1一样,后续事件都不会再分发给任何子View,ViewGroup又想起来自己是个View,调用自身的dispatchTouchEvent()方法处理该ACTION_DOWN事件。
MotionEvent事件从ViewGroup到View的分发流程大致是这样,比较重要的总结如下
结论1.如果ACTION_DOWN没有被子View处理(这里包括ViewGroup拦截了ACTION_DOWN事件和子View没有处理ACTION_DOWN),那么后续的ACTION_MOVE和ACTION_UP事件就不会被分发到子View。
结论2.如果ACTION_DOWN事件被子View处理了,那么后续ACTION_MOVE事件默认会去找之前处理了ACTION_DOWN事件的子View处理,即mFirstTouchTarget,但是ViewGroup依然可以在onInterceptTouchEvent()方法中拦截ACTION_MOVE事件,并处理后续ACTION_MOVE事件。(这是外部拦截法的实现原理)
3.3 处理——View
View是事件分发流程的终点站,无论是ViewGroup传递给子View,子View处理了该事件;还是子View没有处理该事件,ViewGroup调用super.dispatchTouchEvent(),最终都是调用View.dispatchTouchEvent()方法。下面继续分析View.dispatchTouchEvent()方法。
// View
/**
* 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.
*/
// 此方法有返回值 返回true表示View处理了该事件 返回false表示不处理该事件
public boolean dispatchTouchEvent(MotionEvent event) {
if (mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onTouchEvent(event, 0);
}
if (onFilterTouchEventForSecurity(event)) {
//noinspection SimplifiableIfStatement
ListenerInfo li = mListenerInfo;
// 如果View设置了mOnTouchListener 并且mOnTouchListener的onTouch()方法返回true 则直接返回true
// 不会再执行后面的onTouchEvent方法在
if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
&& li.mOnTouchListener.onTouch(this, event)) {
return true;
}
// onTouchEvent()方法中会调用判断View是否是CLICKABLE或LONG_CLICKABLE
// 如果是的话 继续调用mOnClickListener.onClick()方法(如果设置了的话)
if (onTouchEvent(event)) {
return true;
}
}
if (mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
}
return false;
}
View的dispatchTouchEvent方法相对于ViewGroup就要简单很多,主要是先对onTouchListener和mOnTouchListener.onTouch()方法进行判断,均为true则直接返回true;否则继续执行onTouchEvent()方法,在onTouchEvent()中,只要View是CLICKABLE或LONG_CLICKABLE,默认返回true,即默认会消耗事件。
结论1.View的onTouchListener.onTouch()方法返回true,会直接拦截并处理事件,会导致View的onTouchEvent()无法执行,进而导致View的onClickListener.onClick()不执行。
结论2.如果View的onTouchListener.onTouch()方法返回为false,那么默认情况下,只要View是CLICKABLE或LONG_CLICKABLE,则默认处理事件。
结论3.View.dispatchTouchEvent()返回值说明了View对此事件的处理情况,true表示处理,false表示不处理。