事件分发机制——View 与 ViewGroup
1. View和ViewGroup的事件处理分工
// ViewGroup 负责“分发事件”,即决定事件由谁处理(自己还是子View)
ViewGroup.dispatchTouchEvent() ---> 负责分发流程的逻辑
// View 负责“消费事件”,即具体如何响应(如点击、长按)
View.dispatchTouchEvent() ---> 负责事件的最终处理,内部包含onTouchEvent的调用
2. 事件注册与分发流程(系统级调用)
事件注册入口在 ViewRootImpl,每个Activity的Window只有一个ViewRootImpl,是所有View的parent。它负责:
- 事件分发
- 界面刷新
- 与 SurfaceFlinger 通信
- Canvas 创建等
简化调用链(以触摸事件为例):
-
注册事件:
setView@ViewRootImpl.java -> mInputEventReceiver = new WindowInputEventReceiver(inputChannel, Looper.myLooper()); -
事件分发:
WindowInputEventReceiver.onInputEvent(event) -> doProcessInputEvents -> deliverInputEvent -> InputStage.deliver(q) // 多个stage,逐步传递 -> ViewPostImeInputStage.onProcess -> processKeyEvent 或 processPointerEvent -> mView.dispatchTouchEvent(event) // mView通常是DecorView

-
最终进入 Activity 回调:
final Window.Callback cb = mWindow.getCallback(); // Activity if (cb != null && mFeatureId < 0) { cb.dispatchKeyEvent(event) // Activity } else { super.dispatchKeyEvent(event); } // ... win.superDispatchTouchEvent(event) // PhoneWindow -> mDecor.superDispatchTouchEvent(event) -> super.dispatchTouchEvent(event) // DecorView (ViewGroup) -> ViewGroup.dispatchTouchEvent() -> View.dispatchTouchEvent() -> View.onTouch() -> View.onTouchEvent() -> onClick() -> onLongClick() // 由 postDelay Runnable 实现
- 小结: 事件先到 DecorView(Activity的顶层View),再分发到具体View,分发链路极长,每一层都可以“截获”或“中断”事件。
3. InputStage 机制
Input事件(QueuedInputEvent)会经过多级 InputStage 处理,每个Stage负责不同逻辑:
// 顺序从上到下(stage.next指向下一个stage)
SyntheticInputStage
↑
ViewPostImeInputStage
↑
NativePostImeInputStage
↑
EarlyPostImeInputStage
↑
ImeInputStage
↑
ViewPreImeInputStage
↑
NativePreImeInputStage
![image.png]
- 结论: 每个事件依次经过多个Stage,每一层可做预处理、过滤、转发等。最终事件进入DecorView,然后Activity/ViewGroup/View处理。
4. 事件处理相关的关键方法
dispatchTouchEvent—— 所有View都会收到此方法调用,决定事件是否往下传递/分发/拦截。onInterceptTouchEvent—— 仅ViewGroup有,决定事件是否被自己拦截,不再传给子View。onTouchEvent—— 事件被真正消费/处理的地方。
重要细节说明
-
onTouchEvent 在
View.dispatchTouchEvent()内部调用。 -
onTouch 和 onClick 的执行顺序:
onTouch先于onClick,且 onTouch 返回 false 时,才继续执行 onClick。 -
onLongClick 通过
postDelayed实现(按压超过 400ms 后执行)。 -
手指移出View,onClick 不执行,但 LongClick 可能执行,逻辑如下:
if (!pointInView(x, y, touchSlop)) { // 移出View,取消Tap和长按 removeTapCallback(); removeLongPressCallback(); if ((mPrivateFlags & PFLAG_PRESSED) != 0) { setPressed(false); } mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN; }-
上述代码在 ACTION_MOVE 事件中实时检测手指是否超出View范围。超出则取消点击/长按,但长按的延时回调(Runnable)如果已在队列,仍可能触发。
-
进一步逻辑补充:
// 部分情况下,如果只是暂时离开 View,可延长 long press 超时时间 removeLongPressCallback(); long delay = ViewConfiguration.getLongPressTimeout() * mAmbiguousGestureMultiplier; delay -= event.getEventTime() - event.getDownTime(); checkForLongClick(delay, x, y, TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__LONG_PRESS);
-
事件分发代码详解
``java // 事件到达 View 的分发流程(伪代码) View.dispatchTouchEvent() -> if (mOnTouchListener != null) mOnTouchListener.onTouch() -> !result && onTouchEvent(event) // 只有onTouch返回false时才执行onTouchEvent -> switch (event.getAction()) case MotionEvent.ACTION_UP: PerformClick -> performClickInternal -> performClick -> onClick // 事件被最终消费
* **结论:**
* 如果 `setOnTouchListener()`,onTouch 返回 true,则事件被消费,不会再执行 onClick。
* 如果返回 false,则走 onTouchEvent,最终调用 onClick。
***
## 5. ViewGroup的多点触控事件
* 第一根手指按下为 `ACTION_DOWN`,后续第二\~n根为 `ACTION_POINTER_DOWN`。
* 移动过程为 `ACTION_MOVE`(多次回调)。
* 手指抬起,倒数第n根为 `ACTION_POINTER_UP`,最后一根为 `ACTION_UP`。
* **安卓最多支持32根手指(与int位数相关)** ,用位运算区分。
```java
int idBitsToAssign = split ? 1 << ev.getPointerId(actionIndex) : TouchTarget.ALL_POINTER_IDS;
- 其中
pointerId决定具体哪一根手指,便于多点触控精确分发。
6. 小结
- 事件分发入口在 ViewRootImpl,最终到 DecorView/Activity。
- ViewGroup 决定事件分发、拦截,View 决定事件消费。
- dispatchTouchEvent、onInterceptTouchEvent、onTouchEvent 是三大核心钩子。
- 多点触控 用位运算管理不同手指,Android平台天生支持。
事件处理机制的几个重要方法
dispatchTouchEvent:事件到View一定会执行onInterceptTouchEvent:ViewGroup用来拦截事件(只ViewGroup有)onTouchEvent:事件的最终消费点(onClick/onLongClick/自定义处理)
(1)onTouchEvent在哪里执行的-->在View的dispatchTouchEvent中。
(2)onTouch和onClick 执行的位置,onTouch先执行,onClick后执行。
(3)LongClick // ACTION_DOWN处理,removeLongPressCallback(); 按压时间<400,action_down处理
(4)按下移出view,为什么onClick不执行,不过long事件依然可以执行。 // if (!pointInView(x, y, touchSlop)) 原因如下:
if (!pointInView(x, y, touchSlop)) {
// Outside button
// Remove any future long press/tap checks
removeTapCallback();
removeLongPressCallback();
if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
setPressed(false);
}
mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
}
上边这个这个代码是在Move里边执行的,会实时检测位置。
if (!pointInView(x, y, touchSlop)) {
// The default action here is to cancel long press. But instead, we
// just extend the timeout here, in case the classification
// stays ambiguous.
removeLongPressCallback();
long delay = (long) (ViewConfiguration.getLongPressTimeout()
* mAmbiguousGestureMultiplier);
// Subtract the time already spent
delay -= event.getEventTime() - event.getDownTime();
checkForLongClick(
delay,
x,
y,
TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__LONG_PRESS);
}
touchSlop *= mAmbiguousGestureMultiplier;
根据上边的代码,Long事件依然可以响应。
if ((mPrivateFlags & PFLAG_PRESSED) != 0 才能进入onClick,移除了点击与长按事件。
View.dispatchTouchEvent
--->onTouch // 设置setOnTouchListener()之后就会执行,返回值影响onClick执行,false才能继续执行。
--->!result && onTouchEvent(event) // 短路与,当result为true,onTouchEvent不执行。onClick在onTouchEvent里边。
// MotionEvent.ACTION_UP:
---->PerformClick
--->performClickInternal
--->performClick
--->onClick // 表示该事件被这个View消费了。
ViewGroup.dispatchTouchEvent
第一根手指按下:Action_down,第二根到第n根,action_point_down中间移动 ,Action_move多次调用。 抬起:倒数第n根到倒数第二根:Action_point_up,最后一根手指:Action_up。安卓手机最多能够识别32根手指,和int的位数相关。 位运算。一位表示一个手指:
int idBitsToAssign = split ? 1 << ev.getPointerId(actionIndex) : TouchTarget.ALL_POINTER_IDS;
事件分发解析
整体流程如下

Activity.dispatchTouchEvent()
↓
DecorView.dispatchTouchEvent()
↓
Root View (e.g., LinearLayout) dispatchTouchEvent()
↓
[ViewGroup]: onInterceptTouchEvent() → true → Handle in ViewGroup
↓ ↘ false
Child View dispatchTouchEvent() → onTouchEvent()
ViewGroup.dispatchTouchEvent源码
思维导图:
dispatchTouchEvent(ev)
├── 辅助校验
├── DOWN清理
├── onInterceptTouchEvent (父是否拦截)
├── [不拦截]——找target(倒序遍历子View,谁愿意消费给谁)
│ └── (有target) -> addTouchTarget链表
├── [派发事件]
│ ├── (没target) -> ViewGroup自己onTouchEvent
│ └── (有target) -> 链表遍历派发到child
│ └── 父View随时可打断(cancel/remove target)
├── 状态收尾(UP/CANCEL重置)
└── 返回handled
源码分析:
@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;
// Handle an initial down.
// 多指或者单指,只会执行一次。第二、三等手指按下,是Action_point_down
// 重置状态,防止子View申请获取事件之后,本次事件流结束之后(DOWN->UP 或者 DOWN->cancel),父View无法再处理事件
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.检测是否拦截,父容器的权利。mFirstTouchTarget指的事触控的时候,处理事件的头链表,可能是一个,也可能是多个。取决于是否是多指触控。
final boolean intercepted;
if (actionMasked == MotionEvent.ACTION_DOWN
|| mFirstTouchTarget != null) {
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
// 决定onInterceptTouchEvent是否执行。
if (!disallowIntercept) {
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;
// split默认为true,是否可以多指。
final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0
&& !isMouseEvent;
TouchTarget newTouchTarget = null;
boolean alreadyDispatchedToNewTouchTarget = false;
// 在if中分发事件。
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;
// 第一根手指按下时。
if (actionMasked == MotionEvent.ACTION_DOWN
// 只要有手指按下,第二根,第三根...(多指触控)
|| (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)
// 鼠标
|| actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
// 如果事件是MotionEvent.ACTION_DOWN,actionIndex = 0;用来进行事件的计数,如果是第二根第三个手指,这个相应的就是1、2......
final int actionIndex = ev.getActionIndex(); // always 0 for down
// 手指的ID。这里是一个位运算,一位表示一根手指,int是32为,因此安卓手机最多能够识别32根手指
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.
// 将子View进行排序,确定谁来优先处理事件。
final ArrayList<View> preorderedList = buildTouchDispatchChildList();
final boolean customOrder = preorderedList == null
&& isChildrenDrawingOrderEnabled();
final View[] children = mChildren;
// 倒叙遍历。xml写在后边的先处理事件。
for (int i = childrenCount - 1; i >= 0; i--) {
final int childIndex = getAndVerifyPreorderedIndex(
childrenCount, i, customOrder);
final View child = getAndVerifyPreorderedView(
preorderedList, children, childIndex);
// 判断这个view是否能够处理点击事件。
if (!child.canReceivePointerEvents() // View可见或者Animation不为空
// 点击区域是否在View上边
|| !isTransformedTouchPointInView(x, y, child, null)) {
continue;
}
// 单指操作拿到的值为空,会走赋值操作,多指不为空。
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是否处理事件,如果child处理,则命中if--递归
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();
// 创建了newTouchTarget,并且newTouchTarget = mFirstTouchTarget,如果是多指操作,那么addTouchTarget(里边是链表)会将这些target指向下一个目标,
newTouchTarget = addTouchTarget(child, idBitsToAssign);
// 后边会用到。
alreadyDispatchedToNewTouchTarget = true;
// 退出循环,事件已经处理完成,不在询问其他Child
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 (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.
// 没有child处理事件的时候,这个值才是空。
if (mFirstTouchTarget == null) {
// No touch targets so treat this as an ordinary view.
// 所有的Child都不处理,就询问自己是否处理
handled = dispatchTransformedTouchEvent(ev, canceled, null,
TouchTarget.ALL_POINTER_IDS);
} else {
// 有子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循环为单指操作时,只会执行一次。
while (target != null) {
// 单指操作next = null;
final TouchTarget next = target.next;
// 单指操作会直接命中if,直接返回,不做处理。
if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
handled = true;
} else {
final boolean cancelChild = resetCancelNextUpFlag(target.child)
|| intercepted;
// 询问target.child(前面保存的addTouchTarget())要不要处理这个事件
if (dispatchTransformedTouchEvent(ev, cancelChild,
target.child, target.pointerIdBits)) {
handled = true;
}
// 为true,取消child处理事件。
if (cancelChild) {
if (predecessor == null) {
// mFirstTouchTarget置为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进行排列,用来处理事件。显示在最上边的优先处理事件。
ArrayList<View> buildOrderedChildList() {
final int childrenCount = mChildrenCount;
if (childrenCount <= 1 || !hasChildWithZ()) return null;
if (mPreSortedChildren == null) {
mPreSortedChildren = new ArrayList<>(childrenCount);
} else {
// callers should clear, so clear shouldn't be necessary, but for safety...
mPreSortedChildren.clear();
mPreSortedChildren.ensureCapacity(childrenCount);
}
final boolean customOrder = isChildrenDrawingOrderEnabled();
for (int i = 0; i < childrenCount; i++) {
// add next child (in child order) to end of list
final int childIndex = getAndVerifyPreorderedIndex(childrenCount, i, customOrder);
final View nextChild = mChildren[childIndex];
// 默认不设置,则为0
final float currentZ = nextChild.getZ();
// insert ahead of any Views with greater Z
int insertIndex = i;
while (insertIndex > 0 && mPreSortedChildren.get(insertIndex - 1).getZ() > currentZ) {
insertIndex--;
}
// 谁显示在最上边,xml中,布局靠后的放在集合后边。谁最先处理事件
mPreSortedChildren.add(insertIndex, nextChild);
}
return mPreSortedChildren;
}
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) {
// Viewgroup的super就是View.dispatchTouchEvent(处理事件)
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());
}
// child是容器,ViewGroup.dispathTouchEvent。Child是View,View.dispatchTouchEvent(处理事件)
handled = child.dispatchTouchEvent(transformedEvent);
}
// Done.
transformedEvent.recycle();
return handled;
}
// 多指操作组合成链表。
private TouchTarget addTouchTarget(@NonNull View child, int pointerIdBits) {
final TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
// 单指操作,target0->next为空。
target.next = mFirstTouchTarget;
mFirstTouchTarget = target;
return target;
}
View.dispatchTouchEvent负责完成事件的处理
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();
}
if (onFilterTouchEventForSecurity(event)) {
if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
result = true;
}
//noinspection SimplifiableIfStatement
ListenerInfo li = mListenerInfo;
// 首先处理onTouch事件。
if (li != null && li.mOnTouchListener != null
&& (mViewFlags & ENABLED_MASK) == ENABLED
&& li.mOnTouchListener.onTouch(this, event)) {
result = true;
}
// 然后处理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;
}
public boolean onTouchEvent(MotionEvent event) {
// 这里可以实现拓展点击区域的操作
if (mTouchDelegate != null) {
if (mTouchDelegate.onTouchEvent(event)) {
return true;
}
}
if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
switch (action) {
case MotionEvent.ACTION_UP:
mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
if ((viewFlags & TOOLTIP) == TOOLTIP) {
handleTooltipUp();
}
if (!clickable) {
removeTapCallback();
removeLongPressCallback();
mInContextButtonPress = false;
mHasPerformedLongPress = false;
mIgnoreNextUpEvent = false;
break;
}
boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
// take focus if we don't have it already and we should in
// touch mode.
boolean focusTaken = false;
if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
focusTaken = requestFocus();
}
if (prepressed) {
// The button is being released before we actually
// showed it as pressed. Make it show the pressed
// state now (before scheduling the click) to ensure
// the user sees it.
setPressed(true, x, y);
}
if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
// This is a tap, so remove the longpress check
removeLongPressCallback();
// Only perform take click actions if we were in the pressed state
if (!focusTaken) {
// Use a Runnable and post this rather than calling
// performClick directly. This lets other visual state
// of the view update before click actions start.
if (mPerformClick == null) {
mPerformClick = new PerformClick();
}
// onClick 事件在Action_up才会触发,另外,如果在抬起手指的时候已经离开View的区域了,就不会触发了。
if (!post(mPerformClick)) {
performClickInternal();
}
}
}
if (mUnsetPressedState == null) {
mUnsetPressedState = new UnsetPressedState();
}
if (prepressed) {
postDelayed(mUnsetPressedState,
ViewConfiguration.getPressedStateDuration());
} else if (!post(mUnsetPressedState)) {
// If the post failed, unpress right now
mUnsetPressedState.run();
}
removeTapCallback();
}
mIgnoreNextUpEvent = false;
break;
case MotionEvent.ACTION_DOWN:
if (event.getSource() == InputDevice.SOURCE_TOUCHSCREEN) {
mPrivateFlags3 |= PFLAG3_FINGER_DOWN;
}
mHasPerformedLongPress = false;
if (!clickable) {
checkForLongClick(
ViewConfiguration.getLongPressTimeout(),
x,
y,
TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__LONG_PRESS);
break;
}
if (performButtonActionOnTouchDown(event)) {
break;
}
// Walk up the hierarchy to determine if we're inside a scrolling container.
boolean isInScrollingContainer = isInScrollingContainer();
// For views inside a scrolling container, delay the pressed feedback for
// a short period in case this is a scroll.
if (isInScrollingContainer) {
mPrivateFlags |= PFLAG_PREPRESSED;
if (mPendingCheckForTap == null) {
mPendingCheckForTap = new CheckForTap();
}
mPendingCheckForTap.x = event.getX();
mPendingCheckForTap.y = event.getY();
postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
} else {
// Not inside a scrolling container, so show the feedback right away
setPressed(true, x, y);
// 在Action_down事件里边检测和触发long事件。
checkForLongClick(
ViewConfiguration.getLongPressTimeout(),
x,
y,
TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__LONG_PRESS);
}
break;
case MotionEvent.ACTION_CANCEL:
if (clickable) {
setPressed(false);
}
removeTapCallback();
removeLongPressCallback();
mInContextButtonPress = false;
mHasPerformedLongPress = false;
mIgnoreNextUpEvent = false;
mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
break;
case MotionEvent.ACTION_MOVE:
if (clickable) {
drawableHotspotChanged(x, y);
}
final int motionClassification = event.getClassification();
final boolean ambiguousGesture =
motionClassification == MotionEvent.CLASSIFICATION_AMBIGUOUS_GESTURE;
int touchSlop = mTouchSlop;
if (ambiguousGesture && hasPendingLongPressCallback()) {
if (!pointInView(x, y, touchSlop)) {
// The default action here is to cancel long press. But instead, we
// just extend the timeout here, in case the classification
// stays ambiguous.
removeLongPressCallback();
long delay = (long) (ViewConfiguration.getLongPressTimeout()
* mAmbiguousGestureMultiplier);
// Subtract the time already spent
delay -= event.getEventTime() - event.getDownTime();
checkForLongClick(
delay,
x,
y,
TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__LONG_PRESS);
}
touchSlop *= mAmbiguousGestureMultiplier;
}
// Be lenient about moving outside of buttons
if (!pointInView(x, y, touchSlop)) {
// Outside button
// Remove any future long press/tap checks
removeTapCallback();
removeLongPressCallback();
if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
setPressed(false);
}
mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
}
final boolean deepPress =
motionClassification == MotionEvent.CLASSIFICATION_DEEP_PRESS;
if (deepPress && hasPendingLongPressCallback()) {
// process the long click action immediately
removeLongPressCallback();
checkForLongClick(
0 /* send immediately */,
x,
y,
TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__DEEP_PRESS);
}
break;
}
return true;
}
return false;
}
View的onTouchEvent源码解析:
// 总体上就是点击 长按 右键点击的处理。
public boolean onTouchEvent(MotionEvent event) {
final float x = event.getX();
final float y = event.getY();
final int viewFlags = mViewFlags;
final int action = event.getAction();
final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE
|| (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
|| (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
if ((viewFlags & ENABLED_MASK) == DISABLED
&& (mPrivateFlags4 & PFLAG4_ALLOW_CLICK_WHEN_DISABLED) == 0) {
if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
setPressed(false);
}
mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
// A disabled view that is clickable still consumes the touch
// events, it just doesn't respond to them.可以防止点击事件被父View使用而引发的一些点击Bug
return clickable;
}
if (mTouchDelegate != null) {
if (mTouchDelegate.onTouchEvent(event)) {
return true;
}
}
if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
switch (action) {
case MotionEvent.ACTION_UP:
mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
// 让TOOLTIP消失
if ((viewFlags & TOOLTIP) == TOOLTIP) {
handleTooltipUp();
}
if (!clickable) {
removeTapCallback();
removeLongPressCallback();
mInContextButtonPress = false;
mHasPerformedLongPress = false;
mIgnoreNextUpEvent = false;
break;
}
boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
// take focus if we don't have it already and we should in
// touch mode(对了大部分View来说没有什么影响,EditText除外,他需要在焦点获取之后才能开始编辑).
boolean focusTaken = false;
if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
focusTaken = requestFocus();
}
if (prepressed) {
// The button is being released before we actually
// showed it as pressed. Make it show the pressed
// state now (before scheduling the click) to ensure
// the user sees it.
setPressed(true, x, y);
}
if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
// This is a tap, so remove the longpress check
removeLongPressCallback();
// Only perform take click actions if we were in the pressed state
if (!focusTaken) {
// Use a Runnable and post this rather than calling
// performClick directly. This lets other visual state
// of the view update before click actions start.
if (mPerformClick == null) {
mPerformClick = new PerformClick();
}
// 不是预按下就会触发点击监听。
if (!post(mPerformClick)) {
performClickInternal();
}
}
}
if (mUnsetPressedState == null) {
mUnsetPressedState = new UnsetPressedState();
}
if (prepressed) {
postDelayed(mUnsetPressedState,
ViewConfiguration.getPressedStateDuration());
} else if (!post(mUnsetPressedState)) {
// If the post failed, unpress right now
mUnsetPressedState.run();
}
removeTapCallback();
}
mIgnoreNextUpEvent = false;
break;
case MotionEvent.ACTION_DOWN:
// 判断是否是触摸屏幕,因为有些设备是通过遥控器等按键控制的。
if (event.getSource() == InputDevice.SOURCE_TOUCHSCREEN) {
mPrivateFlags3 |= PFLAG3_FINGER_DOWN;
}
mHasPerformedLongPress = false;
// 这个判断是为了TOOLTIP增加的,用来长按显示提示。
if (!clickable) {
checkForLongClick(
ViewConfiguration.getLongPressTimeout(),
x,
y,
TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__LONG_PRESS);
break;
}
// 判断鼠标右键点击。
if (performButtonActionOnTouchDown(event)) {
break;
}
// Walk up the hierarchy to determine if we're inside a scrolling container.
// 两个问题(1)为什么判断自己的ViewTree中是否存在滑动控件?(2)判断了有什么用?
// 这两个判断其实都是为了提升用户体验的
boolean isInScrollingContainer = isInScrollingContainer();
// For views inside a scrolling container, delay the pressed feedback for
// a short period in case this is a scroll.提升用户体验的逻辑,
// 通过增加延时来判断是点击还是滑动。通过延时来确定用户到底是操作父View还是子View
if (isInScrollingContainer) {
mPrivateFlags |= PFLAG_PREPRESSED; // 预按下。
if (mPendingCheckForTap == null) {
mPendingCheckForTap = new CheckForTap();
}
mPendingCheckForTap.x = event.getX();
mPendingCheckForTap.y = event.getY();
// 等待100ms执行
postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
} else {
// Not inside a scrolling container, so show the feedback right away, 标记为按下
setPressed(true, x, y);
checkForLongClick(
ViewConfiguration.getLongPressTimeout(),
x,
y,
TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__LONG_PRESS //500ms);
}
break;
case MotionEvent.ACTION_CANCEL:
if (clickable) {
setPressed(false);
}
removeTapCallback();
removeLongPressCallback();
mInContextButtonPress = false;
mHasPerformedLongPress = false;
mIgnoreNextUpEvent = false;
mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
break;
case MotionEvent.ACTION_MOVE:
if (clickable) {
// 波纹效果
drawableHotspotChanged(x, y);
}
final int motionClassification = event.getClassification();
// 用来处理全屏手势与长按事件冲突的逻辑。
final boolean ambiguousGesture =
motionClassification == MotionEvent.CLASSIFICATION_AMBIGUOUS_GESTURE;
int touchSlop = mTouchSlop;
if (ambiguousGesture && hasPendingLongPressCallback()) {
if (!pointInView(x, y, touchSlop)) {
// The default action here is to cancel long press. But instead, we
// just extend the timeout here, in case the classification
// stays ambiguous.
removeLongPressCallback();
long delay = (long) (ViewConfiguration.getLongPressTimeout()
* mAmbiguousGestureMultiplier);
// Subtract the time already spent
delay -= event.getEventTime() - event.getDownTime();
checkForLongClick(
delay,
x,
y,
TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__LONG_PRESS);
}
touchSlop *= mAmbiguousGestureMultiplier;
}
// Be lenient about moving outside of buttons
// 作用在View之上,按住之后脱离了View的范围,然后又回到View,此时任何时间需要再这个离开又回来的时间只能取消掉,slop是为了处理一定距离的误触而设置的
if (!pointInView(x, y, touchSlop)) {
// Outside button
// Remove any future long press/tap checks
removeTapCallback();
removeLongPressCallback();
if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
setPressed(false);
}
mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
}
// 用力按屏幕的话直接触发长按
final boolean deepPress =
motionClassification == MotionEvent.CLASSIFICATION_DEEP_PRESS;
if (deepPress && hasPendingLongPressCallback()) {
// process the long click action immediately
removeLongPressCallback();
checkForLongClick(
0 /* send immediately */,
x,
y,
TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__DEEP_PRESS);
}
break;
}
return true;
}
return false;
}
整个流程其实就是在执行这个代码:
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
onUserInteraction();
}
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
}
相比于View,ViewGroup不仅要做时间分发,还可能需要做事件响应处理。

一些问题
1. 如果一个View没有接收到ActionDown事件,那么它也无法接受这组事件的后续任何事件,这种说法是否存在问题?
简答:
大多数情况下是成立的,但存在一些例外和需要注意的细节。
详解
1)正常情况
- Android 触摸事件分发以
ACTION_DOWN为起点,只有收到ACTION_DOWN的 View 才会成为本轮触摸事件的“事件目标”(TouchTarget)。 - 后续的
ACTION_MOVE、ACTION_UP等事件默认只会分发给接收到ACTION_DOWN的 View。
2)父View拦截的影响
- 如果父View在
onInterceptTouchEvent()返回了true,会截断事件流,子View只能收到ACTION_DOWN,后续事件会直接分发给父View,不再下发到该子View。 - 如果子View连
ACTION_DOWN都没收到(比如不在点击区域),则不会收到任何事件。
3)父View动态放弃/转交事件
- 如果父View在
ACTION_MOVE阶段调用requestDisallowInterceptTouchEvent(true),后续事件可以继续下发给子View,但前提是子View最初收到了ACTION_DOWN。 - 极少数场景下,父View可以手动调用子View的
dispatchTouchEvent(),将事件“插手”给子View,但这不是标准做法。
4)多点触控例外
- 多点触控下,
ACTION_POINTER_DOWN/UP的事件目标,可以根据新的触控点动态分配。理论上某些View可能在没有收到最初的ACTION_DOWN时,被加入TouchTarget链表,处理新手指的事件。但Android源码中,一般也是以首个ACTION_DOWN为入口。
5)非传统触摸事件
- 某些特殊事件(如
ACTION_HOVER_MOVE、ACTION_SCROLL等)不走常规触摸事件流,可以被独立分发给View,与ACTION_DOWN无关。
6)事件被父View“重新分发”
- 如果View在
ACTION_DOWN时返回false,它不会成为事件目标。但父View依然可以通过“非常规方式”再次把事件分发给它(如强制调用dispatchTouchEvent),但这完全依赖开发者控制,非标准行为。
总结:
在绝大多数实际开发和源码设计下,“没有收到 ACTION_DOWN 的 View 不会收到同一事件序列的后续事件”是对的。只有通过特殊手段才能打破这个规则。
2. 单指操作时,不需要考虑链表问题,因为只有一个 Target
解析:
- Android事件分发中的 TouchTarget 链表机制是为了解决多点触控下多个 View 需要分别接收各自手指事件的情况。
- 单指操作时,只有一个手指,TouchTarget 链表只有一个节点,等价于没有链表。
- 源码里对“单指”情形下链表的逻辑和性能开销非常小,可当作普通变量使用。
3. 继承 Activity 和 AppCompatActivity 的区别
Activity是Android原生的基础组件,支持基本的生命周期和UI管理。AppCompatActivity继承自FragmentActivity,是AndroidX/Support库提供的兼容性Activity,支持更多Material特性和新版本API(如Toolbar、夜间模式等),建议开发时优先使用。- 若只用原生控件、无Fragment需求,可以用
Activity,但绝大多数实际项目都用AppCompatActivity。
4. getAction() 与 getActionMasked() 的区别
| 特性 | getAction() | getActionMasked() |
|---|---|---|
| 返回内容 | 动作码+指针索引 | 仅动作码(低8位) |
| 解析方式 | 需手动位运算解析指针索引 | 直接用作事件类型 |
| 用途 | 适合多点触控指针区分 | 适合判断事件类型 |
建议:
- 判断事件类型用
getActionMasked()(如:ACTION_DOWN,ACTION_MOVE,ACTION_UP)。 - 需要指针索引(哪根手指)时,用
getAction()后自己位运算提取actionIndex。
5. 一个View接受事件后,各个方法的调用时机?
标准流程:
-
View的
dispatchTouchEvent()首先被调用 -
如果设置了
OnTouchListener,则先执行onTouch(),返回true则事件到此结束,不再执行后续 -
如果未消费或返回false,调用
onTouchEvent()- 在
onTouchEvent()内部,自动处理onClick和onLongClick等事件 onLongClick会在ACTION_DOWN后一段延时(一般500ms)触发onClick会在ACTION_UP且未发生滑动/长按时触发
- 在
时间线举例:
- 用户按下 →
dispatchTouchEvent(ACTION_DOWN)→onTouch(ACTION_DOWN)→onTouchEvent(ACTION_DOWN) - 用户抬起 →
dispatchTouchEvent(ACTION_UP)→onTouch(ACTION_UP)→onTouchEvent(ACTION_UP)→onClick(若无滑动且未长按) - 长按 →
dispatchTouchEvent(ACTION_DOWN)→onTouchEvent(ACTION_DOWN)→ (500ms后)onLongClick
学后检测
一、单选题
1. 关于 View 事件分发的下列说法,正确的是?
A. 所有 View 的事件都会先走 onTouchEvent
B. 所有事件分发都只能由 ViewGroup 完成
C. 只有 ViewGroup 拥有 dispatchTouchEvent 方法
D. 事件一定先到 dispatchTouchEvent,再可能进入 onTouch 或 onTouchEvent
答案: D
解析: 事件分发的入口是 dispatchTouchEvent,每个 View 和 ViewGroup 都有该方法,ViewGroup 负责分发,View 负责消费。onTouch/onTouchEvent 都是 dispatchTouchEvent 内部调用的。
2. 关于 onInterceptTouchEvent 的描述,下列哪个是正确的?
A. 所有 View 都有 onInterceptTouchEvent
B. onInterceptTouchEvent 只能在 ViewGroup 使用
C. onInterceptTouchEvent 决定是否将事件交给 Activity
D. onInterceptTouchEvent 只影响 ACTION_DOWN 事件
答案: B
解析: onInterceptTouchEvent 仅在 ViewGroup 及其子类中存在,用于决定事件是否拦截,不存在于普通 View。
3. 在下列哪个场景,View 的 onClick 不会被触发?
A. 用户按下后立刻松开
B. 用户按下并长按超过 500ms
C. 用户按下后滑动手指移出 View 区域再松开
D. 用户单指短按并松开
答案: B、C
解析: 长按会触发 onLongClick 不触发 onClick。滑动出 View 区域则按下标记会被清除,松开时不触发 onClick。
二、多选题
4. 关于事件分发与消费的说法,哪些是正确的?
A. ViewGroup 既能分发事件也能消费事件
B. View 只能消费事件,不能分发事件
C. dispatchTouchEvent 决定事件是否继续向下传递
D. onTouchEvent 决定事件是否最终被消费
答案: A、C、D
解析: ViewGroup 能分发和消费(如自己拦截消费),dispatchTouchEvent 决定传递,onTouchEvent 决定消费。View 也有 dispatchTouchEvent(只是不再下发)。
5. 以下哪些场景下,一个 View 可能不会收到事件序列中的 ACTION_UP?
A. 它没有收到 ACTION_DOWN
B. 父 View 在 ACTION_MOVE 时拦截了事件
C. 它在 ACTION_DOWN 时 onTouchEvent 返回 false
D. 父 View 调用了 requestDisallowInterceptTouchEvent(true)
答案: A、B、C
解析: 没有 ACTION_DOWN,则整个序列都不会收到。被父 View 拦截,后续事件归父View,自己收不到。ACTION_DOWN 返回 false,事件向上传递也不再传给自己。requestDisallowInterceptTouchEvent 只影响父是否能再拦截,不能让“没收到 DOWN”的 View 收到 UP。
三、判断题
6. 判断:onTouch 的返回值为 true,则 onClick 一定不会被触发。
( )
答案: 正确
解析: onTouch 返回 true 事件被消费,不再往下走 onTouchEvent,自然不会进入 onClick。
7. 判断:在多点触控情况下,每根手指对应一个 TouchTarget 链表节点。
( )
答案: 正确
解析: 源码用链表管理多指,每个手指对应 View 的 TouchTarget 节点。
8. 判断:View 的 onTouchEvent 一定会被调用。
( )
答案: 错误
解析: 如果 onTouch 返回 true,onTouchEvent 就不会被调用。
四、简答题
9. 简述 Android 事件分发的完整链路(从 Activity 到 View 的顺序)。
答案要点:
- 事件从 ViewRootImpl 进入,传递到 DecorView(Activity 的顶层 View)。
- DecorView.dispatchTouchEvent 调用,逐层传递到最顶级 ViewGroup(如 LinearLayout、FrameLayout)。
- ViewGroup 先走 onInterceptTouchEvent 决定是否拦截,不拦截则传递到子 View。
- 子 View 通过 dispatchTouchEvent、onTouch、onTouchEvent 消费事件。
- 整个过程中,每一层都可以终止分发(如返回 true)。
解析:
事件总是从 Activity 入口,最终按 View 树层层下发,父 View 可随时拦截,只有事件链路上收到 ACTION_DOWN 的 View,才有资格收到后续事件。
10. 为什么在 onTouchEvent 中,长按事件(onLongClick)有时会被触发但 onClick 不会?请举例说明实现原理。
答案要点:
- 长按事件在 ACTION_DOWN 后通过 postDelayed 延时触发(一般 500ms)。
- 如果用户按住超过延时,触发 onLongClick,onClick 不会再被触发(由标志位控制)。
- 如果手指移动离开 View 区域,长按的回调可能还在队列,有可能还是会触发长按,但不会触发 onClick,因为点击标志已被清除。
解析:
源码的 state/flag 控制,保证长按与点击不会重复触发。
五、编程题
11. 编程:请写一段自定义 ViewGroup 代码,要求拦截 ACTION_DOWN 事件(即始终只让自己处理,子 View 不参与),并统计每次点击的次数。
java
public class InterceptAllDownLayout extends ViewGroup {
private int clickCount = 0;
public InterceptAllDownLayout(Context context) {
super(context);
}
public InterceptAllDownLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
// 始终拦截 ACTION_DOWN,自己消费所有触摸事件
return ev.getAction() == MotionEvent.ACTION_DOWN;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
clickCount++;
Log.d("ClickCounter", "点击次数:" + clickCount);
}
return true;
}
// 省略 onLayout 实现
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) { }
}
解析:
- onInterceptTouchEvent 拦截 DOWN,ViewGroup 自己处理事件,子 View 不会收到。
- onTouchEvent 消费事件,统计点击次数。
- 省略 onLayout,仅关注事件分发逻辑。