深色模式
Android 事件分发源码分析
Activity
Activity 分发
java
// Activity.java
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
//第一次按下操作时,用户希望能与设备进行交互,可通过实现该方法
onUserInteraction();
}
//获取当前Activity的顶层窗口是PhoneWindow
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
//当没有任何view处理时,交由activity的onTouchEvent处理
return onTouchEvent(ev);
}
总结:
- Activity 分发事件前,优先级最高的回调是
onUserInteraction()
,可由用户重写此方法。 - Activity 会把事件分发给 PhoneWindow。
- 事件未被消费,则冒泡回到 Activity 的
onTouchEvent()
方法。
PhoneWindow 分发
java
// PhoneWindow.java
public boolean superDispatchTouchEvent(KeyEvent event) {
// 交给DecorView分发,DecorView是一个FrameLayout,所以:
// 从这里开始进行ViewGroup的dispatchTouchEvent流程
return mDecor.superDispatcTouchEvent(event);
}
总结:
PhoneWindow 最终把消息分发给了 DecorView,DecorView 继续分发事件,此时开始走 ViewGroup 的分发流程。
ViewGroup
ViewGroup 分发事件
java
public boolean dispatchTouchEvent(MotionEvent ev) {
//...
boolean handled = false;
//根据隐私策略而来决定是否过滤本次触摸事件,
if (onFilterTouchEventForSecurity(ev)) {
final int action = ev.getAction();
final int actionMasked = action & MotionEvent.ACTION_MASK;
if (actionMasked == MotionEvent.ACTION_DOWN) {
// 发生ACTION_DOWN事件, 则取消并清除之前所有的触摸targets
cancelAndClearTouchTargets(ev);
resetTouchState(); // 重置触摸状态
}
// 发生ACTION_DOWN事件或者已经发生过ACTION_DOWN;才进入此区域,主要功能是拦截器
//只有发生过ACTION_DOWN事件,则mFirstTouchTarget != null;
final boolean intercepted;
if (actionMasked == MotionEvent.ACTION_DOWN
|| mFirstTouchTarget != null) {
//可通过调用requestDisallowInterceptTouchEvent,不让父View拦截事件
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
//判断是否允许调用拦截器
if (!disallowIntercept) {
//调用拦截方法
intercepted = onInterceptTouchEvent(ev);
ev.setAction(action);
} else {
intercepted = false;
}
} else {
// 当没有触摸targets,且不是down事件时,开始持续拦截触摸。
intercepted = true;
}
//...
//不取消事件,同时不拦截事件, 并且是Down事件才进入该区域
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(); // down事件等于0
final int idBitsToAssign = split ? 1 << ev.getPointerId(actionIndex)
: TouchTarget.ALL_POINTER_IDS;
removePointersFromTouchTargets(idBitsToAssign); //清空早先的触摸对象
final int childrenCount = mChildrenCount;
//第一次down事件,同时子视图不会空时
if (newTouchTarget == null && childrenCount != 0) {
final float x = ev.getX(actionIndex);
final float y = ev.getY(actionIndex);
// 从视图最上层到下层,获取所有能接收该事件的子视图
final ArrayList<View> preorderedList = buildOrderedChildList();
final boolean customOrder = preorderedList == null
&& isChildrenDrawingOrderEnabled();
final View[] children = mChildren;
// 从最底层的父视图开始遍历,
// 找寻newTouchTarget,并赋予view与 pointerIdBits;
// 如果已经存在找寻newTouchTarget,说明正在接收触摸事件,则跳出循环
for (int i = childrenCount - 1; i >= 0; i--) {
final int childIndex = customOrder
? getChildDrawingOrder(childrenCount, i) : i;
final View child = (preorderedList == null)
? children[childIndex] : preorderedList.get(childIndex);
// 如果当前视图无法获取用户焦点,则跳过本次循环
if (childWithAccessibilityFocus != null) {
if (childWithAccessibilityFocus != child) {
continue;
}
childWithAccessibilityFocus = null;
i = childrenCount - 1;
}
//如果view不可见,或者触摸的坐标点不在view的范围内,则跳过本次循环
if (!canViewReceivePointerEvents(child)
|| !isTransformedTouchPointInView(x, y, child, null)) {
ev.setTargetAccessibilityFocus(false);
continue;
}
newTouchTarget = getTouchTarget(child);
// 已经开始接收触摸事件,并退出整个循环。
if (newTouchTarget != null) {
newTouchTarget.pointerIdBits |= idBitsToAssign;
break;
}
//重置取消或抬起标志位
//如果触摸位置在child的区域内,则把事件分发给子View或ViewGroup
if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
// 获取TouchDown的时间点
mLastTouchDownTime = ev.getDownTime();
// 获取TouchDown的Index
if (preorderedList != null) {
for (int j = 0; j < childrenCount; j++) {
if (children[childIndex] == mChildren[j]) {
mLastTouchDownIndex = j;
break;
}
}
} else {
mLastTouchDownIndex = childIndex;
}
//获取TouchDown的x,y坐标
mLastTouchDownX = ev.getX();
mLastTouchDownY = ev.getY();
//添加TouchTarget,则mFirstTouchTarget != null。 [见小节2.4.5]
newTouchTarget = addTouchTarget(child, idBitsToAssign);
//表示以及分发给NewTouchTarget
alreadyDispatchedToNewTouchTarget = true;
break;
}
ev.setTargetAccessibilityFocus(false);
}
// 清除视图列表
if (preorderedList != null) preorderedList.clear();
}
if (newTouchTarget == null && mFirstTouchTarget != null) {
//将mFirstTouchTarget的链表最后的touchTarget赋给newTouchTarget
newTouchTarget = mFirstTouchTarget;
while (newTouchTarget.next != null) {
newTouchTarget = newTouchTarget.next;
}
newTouchTarget.pointerIdBits |= idBitsToAssign;
}
}
}
// mFirstTouchTarget赋值是在通过addTouchTarget方法获取的;
// 只有处理ACTION_DOWN事件,才会进入addTouchTarget方法。
// 这也正是当View没有消费ACTION_DOWN事件,则不会接收其他MOVE,UP等事件的原因
if (mFirstTouchTarget == null) {
//没有触摸target,则由当前ViewGroup来处理
handled = dispatchTransformedTouchEvent(ev, canceled, null,
TouchTarget.ALL_POINTER_IDS);
} else {
//如果View消费ACTION_DOWN事件,那么MOVE,UP等事件相继开始执行
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;
}
}
//当发生抬起或取消事件,更新触摸targets
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 (onFilterTouchEventForSecurity(ev))的结尾
//通知verifier由于当前事件未处理,那么该事件其余的都将被忽略
if (!handled && mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onUnhandledEvent(ev, 1);
}
return handled;
}
java
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;
}
final int oldPointerIdBits = event.getPointerIdBits();
final int newPointerIdBits = oldPointerIdBits & desiredPointerIdBits;
//由于某些原因,发生不一致的操作,那么将抛弃该事件
if (newPointerIdBits == 0) {
return false;
}
//分发的主要区域
final MotionEvent transformedEvent;
//判断预期的pointer id与事件的pointer id是否相等
if (newPointerIdBits == oldPointerIdBits) {
if (child == null || child.hasIdentityMatrix()) {
if (child == null) {
//不存在子视图时,ViewGroup调用View.dispatchTouchEvent分发事件,再调用ViewGroup.onTouchEvent来处理事件
handled = super.dispatchTouchEvent(event); // [见小节2.4]
} else {
final float offsetX = mScrollX - child.mLeft;
final float offsetY = mScrollY - child.mTop;
event.offsetLocation(offsetX, offsetY);
//将触摸事件分发给子ViewGroup或View;
//如果是ViewGroup,则调用代码(2.1);
//如果是View,则调用代码(3.1);
handled = child.dispatchTouchEvent(event);
event.offsetLocation(-offsetX, -offsetY); //调整该事件的位置
}
return handled;
}
transformedEvent = MotionEvent.obtain(event); //拷贝该事件,来创建一个新的MotionEvent
} else {
//分离事件,获取包含newPointerIdBits的MotionEvent
transformedEvent = event.split(newPointerIdBits);
}
if (child == null) {
//不存在子视图时,ViewGroup调用View.dispatchTouchEvent分发事件,再调用ViewGroup.onTouchEvent来处理事件
handled = super.dispatchTouchEvent(transformedEvent); // [见小节2.4]
} else {
final float offsetX = mScrollX - child.mLeft;
final float offsetY = mScrollY - child.mTop;
transformedEvent.offsetLocation(offsetX, offsetY);
if (! child.hasIdentityMatrix()) {
//将该视图的矩阵进行转换
transformedEvent.transform(child.getInverseMatrix());
}
//将触摸事件分发给子ViewGroup或View;
//如果是ViewGroup,则 [见小节2.4]; 如果是View,则[见小节2.5];
handled = child.dispatchTouchEvent(transformedEvent);
}
//回收transformedEvent
transformedEvent.recycle();
return handled;
}
总结:
- 先判断是否拦截事件;
- 如果不拦截,还要寻找 TouchTarget;
- 最后分发事件,分发给自己或 TouchTarget。
ViewGroup 拦截事件
java
public boolean onInterceptTouchEvent(MotionEvent ev) {
...
// 默认不拦截
return false;
}
ViewGroup 处理事件
ViewGroup 没有重写 View 的onTouchEvent()
方法,所以 ViewGroup 对事件的处理同 View。
View
View 分发事件
java
public boolean dispatchTouchEvent(MotionEvent event) {
...
final int actionMasked = event.getActionMasked();
if (actionMasked == MotionEvent.ACTION_DOWN) {
//在Down事件之前,如果存在滚动操作则停止。不存在则不进行操作
stopNestedScroll();
}
// mOnTouchListener.onTouch优先于onTouchEvent。
if (onFilterTouchEventForSecurity(event)) {
//当存在OnTouchListener,且视图状态为ENABLED时,调用onTouch()方法
ListenerInfo li = mListenerInfo;
if (li != null && li.mOnTouchListener != null
&& (mViewFlags & ENABLED_MASK) == ENABLED
&& li.mOnTouchListener.onTouch(this, event)) {
result = true; //如果已经消费事件,则返回True
}
//如果OnTouch()没有消费Touch事件则调用OnTouchEvent()
if (!result && onTouchEvent(event)) { // [见小节2.5.1]
result = true; //如果已经消费事件,则返回True
}
}
if (!result && mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
}
// 处理取消或抬起操作
if (actionMasked == MotionEvent.ACTION_UP ||
actionMasked == MotionEvent.ACTION_CANCEL ||
(actionMasked == MotionEvent.ACTION_DOWN && !result)) {
stopNestedScroll();
}
return result;
}
总结:
- 在分发阶段会判断 OnTouchListener,所以 OnTouchListener 处理事件的优先级最高。
- OnTouchListener 不消费事件,则分发给 View 的
onTouchEvent()
。
View 处理事件
java
public boolean onTouchEvent(MotionEvent event) {
final float x = event.getX();
final float y = event.getY();
final int viewFlags = mViewFlags;
// 当View状态为DISABLED,如果可点击或可长按,则返回True,即消费事件
if ((viewFlags & ENABLED_MASK) == DISABLED) {
if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
setPressed(false);
}
return (((viewFlags & CLICKABLE) == CLICKABLE ||
(viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
}
if (mTouchDelegate != null) {
if (mTouchDelegate.onTouchEvent(event)) {
return true;
}
}
//当View状态为ENABLED,如果可点击或可长按,则返回True,即消费事件;
//与前面的的结合,可得出结论:只要view是可点击或可长按,则消费该事件.
if (((viewFlags & CLICKABLE) == CLICKABLE ||
(viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
boolean focusTaken = false;
if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
focusTaken = requestFocus();
}
if (prepressed) {
setPressed(true, x, y);
}
if (!mHasPerformedLongPress) {
//这是Tap操作,移除长按回调方法
removeLongPressCallback();
if (!focusTaken) {
if (mPerformClick == null) {
mPerformClick = new PerformClick();
}
//调用View.OnClickListener
if (!post(mPerformClick)) {
performClick();
}
}
}
if (mUnsetPressedState == null) {
mUnsetPressedState = new UnsetPressedState();
}
if (prepressed) {
postDelayed(mUnsetPressedState,
ViewConfiguration.getPressedStateDuration());
} else if (!post(mUnsetPressedState)) {
mUnsetPressedState.run();
}
removeTapCallback();
}
break;
case MotionEvent.ACTION_DOWN:
mHasPerformedLongPress = false;
if (performButtonActionOnTouchDown(event)) {
break;
}
//获取是否处于可滚动的视图内
boolean isInScrollingContainer = isInScrollingContainer();
if (isInScrollingContainer) {
mPrivateFlags |= PFLAG_PREPRESSED;
if (mPendingCheckForTap == null) {
mPendingCheckForTap = new CheckForTap();
}
mPendingCheckForTap.x = event.getX();
mPendingCheckForTap.y = event.getY();
//当处于可滚动视图内,则延迟TAP_TIMEOUT,再反馈按压状态,用来判断用户是否想要滚动。默认延时为100ms
postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
} else {
//当不再滚动视图内,则立刻反馈按压状态
setPressed(true, x, y);
checkForLongClick(0); //检测是否是长按
}
break;
case MotionEvent.ACTION_CANCEL:
setPressed(false);
removeTapCallback();
removeLongPressCallback();
break;
case MotionEvent.ACTION_MOVE:
drawableHotspotChanged(x, y);
if (!pointInView(x, y, mTouchSlop)) {
removeTapCallback();
if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
removeLongPressCallback();
setPressed(false);
}
}
break;
}
return true;
}
return false;
}
总结:
- 如果 View 为 disabled,那么是否消费事件取决于 View 是否可点击或长按。如果是
CLICKABLE
或LONG_CLICKABLE
都会消费此事件,否则不消费。 - 如果 View 为 enabled,则判断触发 OnClickListener 或 OnLongClickListener。