Android事件分发机制
前言:网上有很多关于Android事件分发的文章,但大多是基于使用经验或者Log来总结出来的,本文主要从源码进行分析,彻底了解Android事件分发的原理。以下的内容都是基于Android7.1源码的。
Activity的事件分发机制
一般情况下,对于应用层来说,事件的分发是从Activity接收到来自系统的TouchEvent开始的。Activity的dispatchTouchEvent首先被调用:
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
// 可以重写这个方法,处理ACTION_DOWN事件,可以看出,任何事件序列都会首先调用这个函数,如果需要监听用户是否触摸屏幕,那么建议重写这个函数即可。
onUserInteraction();
}
// 将事件交由Window处理,返回true表示事件已经消耗掉了,于是返回true告诉系统。
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
// 如果该事件没有被Window消耗掉,那么Activity的TouchEvent将会被调用。
return onTouchEvent(ev);
}
Activity的事件分发比较简单,由源码可以看出,如果Window消耗了事件,或者Activity自身的onTouchEvent消耗了事件,都将会返回true,告诉系统事件已经被消耗掉。
我们知道,一个事件序列基本都是由ACTION_DOWN,ACTION_MOVE...,ACTION_MOVE,ACTION_UP构成的,在Activity的事件分发机制里面,一个事件序列里面的每个子事件的处理都是独立开来的,即,就算Activity不消耗ACTION_DOWN事件,接下来的ACTION_MOVE,ACTION_UP等事件都会继续传递给Activity处理。
Window的事件分发机制
在事件分发的过程中,Window只是作为中间的桥梁,这里没什么好说的。直接源码:
// 这个函数是在PhoneWindow里面的,实际上Activity中的Window,就是一个PhoneWindow
public boolean superDispatchTouchEvent(MotionEvent event) {
// 直接交由DecorView处理
return mDecor.superDispatchTouchEvent(event);
}
ViewGroup的事件分发机制
查看DecorView的源码发现,实际上,就是间接调用ViewGroup的dispatchTouchEvent,因为DecorView继承自FrameLayout,FrameLayout继承自ViewGroup,FrameLayout并没有重写dispatchTouchEvent函数,所以最终调用的是ViewGroup的dispatchTouchEvent。
public boolean superDispatchTouchEvent(MotionEvent event) {
return super.dispatchTouchEvent(event);
}
下面是把一些无关的代码删除后,ViewGroup的dispatchTouchEvent的实现,每一事件序列都维护着一个触摸链表,触摸链表的节点实体是TouchTarget,
事件序列中的任一事件,将会更新触摸链表。触摸链表是当前触点可以触摸到的子View的集合,例如一个ViewGroup中有2个子View,A和B,A和B有重合的部分,
如果手指触摸到重合的部分,那么触摸链表里面就是A和B,如果只是触摸到A独有的部分,那么触摸链表就是只有A。
public boolean dispatchTouchEvent(MotionEvent ev) {
boolean handled = false;
// 过滤一些不安全的触摸事件,比如当前View被别的可见分Window遮挡住了。
if (onFilterTouchEventForSecurity(ev)) {
final int action = ev.getAction();
final int actionMasked = action & MotionEvent.ACTION_MASK;
if (actionMasked == MotionEvent.ACTION_DOWN) {
// 清除之前的事件序列状态,另外,如果上一个事件序列结束后,当前这个ViewGroup被设置成不拦截事件的,
// 那么在这个事件开始时,总是被设置成可以拦截事件。即设置FLAG_DISALLOW_INTERCEPT只是在一个事件序列内有效。
// mFirstTouchTarget也会被清除。
cancelAndClearTouchTargets(ev);
resetTouchState();
}
// Check for interception.
final boolean intercepted;
// 一般情况下,如果是ACTION_DOWN事件,那么mFirstTouchTarget就为null,因为在上面的代码里面,ACTION_DOWN事件将会首先清除触摸链表
// 如果不是ACTION_DOWN,而这个时候mFirstTouchTarget不为null,那么说明,ACTION_DOWN事件已经被当前ViewGroup的某一个子View消耗了
// 于是会继续尝试拦截,于是可以得出:ViewGroup可以在事件序列的任一个节点阻止事件继续往下传递。
if (actionMasked == MotionEvent.ACTION_DOWN
|| mFirstTouchTarget != null) {
// 是否允许拦截事件,记住,FLAG_DISALLOW_INTERCEPT会在ACTION_DOWN事件到来时被重设,所以,
// onInterceptTouchEvent 总是会被调用(ACTION_DOWN事件)
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
if (!disallowIntercept) {
// 我们可以重写ViewGroup的onInterceptTouchEvent来决定要不要拦截事件
intercepted = onInterceptTouchEvent(ev);
ev.setAction(action); // restore action in case it was changed
} else {
intercepted = false;
}
} else {
// 如果不是ACTION_DOWN,而这个时候mFirstTouchTarget又为null,那么说明ACTION_DOWN事件已经被当前的ViewGroup拦截了,或者是
// 没有子View消耗ACTION_DOWN事件,
// 于是,当前ViewGroup应该继续拦截接下来的一个事件序列内的所有事件。
intercepted = true;
}
// 如果事件被拦截了,或者有子View处理了,都进行正常的分发。
if (intercepted || mFirstTouchTarget != null) {
ev.setTargetAccessibilityFocus(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;
TouchTarget newTouchTarget = null;
boolean alreadyDispatchedToNewTouchTarget = false;
// 事件不取消,而且不拦截
if (!canceled && !intercepted) {
// If the event is targeting accessiiblity 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);
final int childrenCount = mChildrenCount;
if (newTouchTarget == null && childrenCount != 0) {
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.
final ArrayList preorderedList = buildTouchDispatchChildList();
final boolean customOrder = preorderedList == null
&& isChildrenDrawingOrderEnabled();
final View[] children = mChildren;
// 遍历所有子View,并将事件分发给子View(如果该子View能接受事件的话)。
for (int i = childrenCount - 1; i >= 0; i--) {
final int childIndex = getAndVerifyPreorderedIndex(
childrenCount, i, customOrder);
final View child = getAndVerifyPreorderedView(
preorderedList, children, childIndex);
// If there is a view that has accessibility focus we want it
// to get the event first and if not handled we will perform a
// normal dispatch. We may do a double iteration but this is
// safer given the timeframe.
if (childWithAccessibilityFocus != null) {
if (childWithAccessibilityFocus != child) {
continue;
}
childWithAccessibilityFocus = null;
i = childrenCount - 1;
}
// View如果不可见,或者事件坐标不在View范围内,那么View不能处理该事件。
if (!canViewReceivePointerEvents(child)
|| !isTransformedTouchPointInView(x, y, child, null)) {
ev.setTargetAccessibilityFocus(false);
continue;
}
// 执行到这里的时候,说明View是具有响应当前事件的能力的(看上面的if语句)
// 假设当前事件不是DOWN事件,那么View应该就在触摸链表中了,即newTouchTarget不为null,
// 于是将会跳出循环
// 例外的情况是:如果是滑动的时候,滑到了一个全新的子View中,newTouchTarget == null,那么就会跑下面的代码
// 将该子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);
// 将事件传递给子View,子View的dispatchTouchEvent被调用
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();
// 这个子view不再触摸链表中,但是其能够响应当前的事件,所以理应将它加入到触摸链表中。
// 将该子View插入到触摸目标的链表头部。
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();
}
// 如果没有找到消耗当前事件的子View,那么最新的触摸目标指向最迟最近的的触摸目标
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;
}
}
}
// Dispatch to touch targets.
if (mFirstTouchTarget == null) {
// mFirstTouchTarget == null 说明触摸链表是空的,表示ViewGroup中没有子View响应该事件,那么
// ViewGroup被当做是View对待,即ViewGroup的父类的dispatchTouchEvent被调用。ViewGroup的父类是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;
// 遍历触摸链表,一个一个分发给链表中的view。
while (target != null) {
final TouchTarget next = target.next;
if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
// 如果分发过了,那么就不再重复分发了
handled = true;
} else {
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;
}
View的事件分发机制
View的事件分发比较简单,如果有设置onTouchListener,那么onTouchListener首先响应事件,
onTouchListener 如果不消耗事件,那么轮到onTouchEvent响应事件,如果连onTouchEvent都不消耗事件,
那么表明该View不消耗事件,返回false,将事件交由父View处理。
public boolean dispatchTouchEvent(MotionEvent event) {
// 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();
}
// 如果当前View被别的可见的Window遮挡,那么无法响应事件
// 例如Toast
if (onFilterTouchEventForSecurity(event)) {
if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
result = true;
}
//noinspection SimplifiableIfStatement
ListenerInfo li = mListenerInfo;
// 如果View有设置OnTouchListener,那么OnTouchListener首先响应事件。
if (li != null && li.mOnTouchListener != null
&& (mViewFlags & ENABLED_MASK) == ENABLED
&& li.mOnTouchListener.onTouch(this, event)) {
result = true;
}
// 如果OnTouchListener不响应事件,那么轮到onTouchEvent响应事件
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;
}