View 的事件分发机制
一、基本概念
1.对点击事件的分发,其实就是对 MotionEvent 事件的分发过程
根据面向对象的思想,事件被封装成了 MotionEvent 对象
2.事件分发的对象是 Touch 事件
3.常见事件
事件 | 动作 |
---|---|
MotionEvent.ACTION_DOWN | 手指在屏幕上按下时触发 |
MotionEvent.ACTION_MOVE | 手指在屏幕上滑动,多次触发 |
MotionEvent.ACTION_UP | 手指离开屏幕时触发 |
MotionEvent.ACTION_CANCEL | 事件被上层拦截(非人为原因) |
4.事件分发中重要的三个函数
函数:public boolean dispatchTouchEvent(MotionEvent ev)
作用:
a. 用来分发事件,事件传递到某个 View 时,当前方法会被调用
b. 返回值受当前 View#onTouchEvent() 和子 View#dispatchTouchEvent() 影响
c. 返回 true:消耗事件;false:不消耗事件
函数:public boolean onInterceptTouchEvent(MotionEvent event)
作用:
a. ViewGroup 用来判断是否拦截当前事件
b. 如果 ViewGroup 拦截,同一事件序列中,当前方法不会被再次调用
c.返回 true:拦截事件;false:不拦截事件
函数:public boolean onTouchEvent(MotionEvent event)
作用:
a. 用来处理事件
b. 返回 true:消耗事件;false:不消耗事件(同一序列的事件,当前 View 无法再接收到事件)
调用关系图(伪代码):
public boolean dispatchTouchEvent(MotionEvent ev) {
boolean consume = false;
if (onInterceptTouchEvent(ev)) {
consume = onTouchEvent(ev);
} else {
consume = child.dispatchTouchEvent(ev);
}
return consume;
}
二、事件分发从 ViewGroup 开始
手机展示给用户的始终是界面,即 Activity。在 Activity 中有一个方法如下图所示
dispatchTouchEvent() 方法是在用户触碰到手机屏幕时执行
第一个 if
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
onUserInteraction();
}
如果事件为 DOWN,则执行第 2422 行的方法,该方法为空方法,没内容
第二个 if
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
调用 Window#superDispatchTouchEvent() 方法
Window#superDispatchTouchEvent() 方法是抽象方法,其子类必定会去实现。其子类 PhoneWindow 实现了 superDispatchTouchEvent() 方法
PhoneWindow 调用了 DecorView#superDispatchTouchEvent() 方法
DecorView 调用 super.dispatchTouchEvent() 方法
DecorView 的父类是 FrameLayout(帧布局)
在 FrameLayout(帧布局)中并没有 dispatchTouchEvent() 方法,FrameLayout(帧布局)父类是 ViewGroup
FrameLayout(帧布局)的父类 ViewGroup 有 dispatchTouchEvent()
因此,事件分发从 ViewGroup 开始
三、ViewGroup 分发事件
点击事件达到 ViewGroup 以后,会调用 ViewGroup#dispatchTouchEvent() 方法
事件分发机制
事件指:点击、滑动、抬起等
事件分发的对象:MotionEvent
三个重要的方法:dispatchTouchEvent()、onInterceptTouchEvent()、onTouchEvent()
dispatchTouchEvent():事件分发
onInterceptTouchEvent():事件拦截
onTouchEvent():事件处理
最先接触事件的是 Activity,最终点击事件从 ViewGroup 开始分发调用 ViewGroup#dispatchTouchEvent() 每一轮事件从处理 DOWN 开始,会重置所有触摸状态,每次都会判断是否需要拦截 DOWN 事件
① 如果不拦截,会执行 addTouchTarget() 方法对 mFirstTouchTarget 进行赋值,之后通过 dispatchTransformedTouchEvent() 方法传递触摸事件
② 如果拦截,直接通过 dispatchTransformedTouchEvent() 方法传递触摸事件,其中会调用 super.dispatchTouchEvent()
ViewGroup 拦截 事件,之后的 MOVE 和 UP 事件不再判断是否拦截,同一序列中的其他事件直接交给 super.dispatchTouchEvent()
ViewGroup#dispatchTouchEvent():
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
...
// 检测是否是按下操作
boolean handled = false;
if (onFilterTouchEventForSecurity(ev)) {
final int action = ev.getAction();
final int actionMasked = action & MotionEvent.ACTION_MASK;
// Handle an initial down.
// 处理新的 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.
// 是否拦截,只能通过 requestDisallowInterceptTouchEvent() 方法更改结果,但是 ViewGroup 必须拦截 DOWN
final boolean intercepted;
// ------------------》关键:判断是否拦截事件《------------------
// 若当前为 DOWN 事件,或目标链表中第一个触摸目标对象不为空(每次遇到 DOWN 事件都需要判断是否需要拦截)
if (actionMasked == MotionEvent.ACTION_DOWN
|| mFirstTouchTarget != null) {
// disallowIntercept 译为禁止拦截,默认为 false,即拦截
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
// disallowIntercept 为假,即需要拦截
if (!disallowIntercept) {
// 执行事件拦截方法 onInterceptTouchEvent(),返回拦截结果
intercepted = onInterceptTouchEvent(ev);
// 恢复操作,防止被更改
ev.setAction(action); // restore action in case it was changed
} else {
intercepted = false;
}
} else { // 当前不是 DOWN 事件,且目标对象为空,需要拦截
// 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 split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;
TouchTarget newTouchTarget = null;
// 没有调度到新的触摸目标
boolean alreadyDispatchedToNewTouchTarget = false;
// 取消为假,且拦截为假时,即当前不取消不拦截(进入事件分发)
if (!canceled && !intercepted) {
...
// 是否为 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 childrenCount = mChildrenCount;
// 触摸目标 newTouchTarget 为空,且子 View 数量不为 0
if (newTouchTarget == null && childrenCount != 0) {
// 手指触摸的 x 轴坐标
final float x = ev.getX(actionIndex);
// 手机触摸的 y 轴坐标
final float y = ev.getY(actionIndex);
// Find a child that can receive the event.
// Scan children from front to back.
// 找一个可以接受事件的子控件(查找可以接受事件的 ChildView)
// 从前往后扫描
// 触摸调度列表 preorderedList
// 对子控件进行排序(因为子控件会存在相互重叠的备份,优先顶层)
final ArrayList<View> preorderedList = buildTouchDispatchChildList();
final boolean customOrder = preorderedList == null
&& isChildrenDrawingOrderEnabled();
final View[] children = mChildren;
// 倒叙遍历(注意,从最后往前扫描)
for (int i = childrenCount - 1; i >= 0; i--) {
// 获取和验证预排序索引
final int childIndex = getAndVerifyPreorderedIndex(
childrenCount, i, customOrder);
// 获取和验证预排序 View
final View child = getAndVerifyPreorderedView(
preorderedList, children, childIndex);
...
// Gets the touch target for specified child view.
// Returns null if not found.
// 得到 Touch 事件对象对应的 View,没找到返回 null
// 获取目标 View
// 判断 child 是否包含在 mFirstTouchTarget 中,如果有就返回 target,反之返回 null
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.
// Child 已经准备好接受在其区域内的事件
newTouchTarget.pointerIdBits |= idBitsToAssign;
// getTouchTarget() 中,从 mFirstTouchTarget 开始找不为空的 target,找到就返回
// 当前进入 if 语句,代表 mFirstTouchTarget 此时不为空,由当前 child 处理事件
// 找到目标 View,跳出当前 for 循环
break;
}
resetCancelNextUpFlag(child);
// 调度转换触摸事件
if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
// Child wants to receive touch within its bounds.
// 记录
mLastTouchDownTime = ev.getDownTime();
// 触摸调度列表 preorderedList 不为 null
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 { // 触摸调度列表 preorderedList 为 null
mLastTouchDownIndex = childIndex;
}
mLastTouchDownX = ev.getX();
mLastTouchDownY = ev.getY();
// ------------------》关键:把 child 加入到触摸列表《------------------
// 将 child 添加到列表的开头,假定目标尚未存在(会对 mFirstTouchTarget 赋值)
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);
}
// 触摸调度列表 preorderedList 不为 null,清空 preorderedList
if (preorderedList != null) preorderedList.clear();
}
// 触摸目标 newTouchTarget 为 null,且目标链表中第一个触摸目标 mFirstTouchTarget 不为 null
if (newTouchTarget == null && mFirstTouchTarget != null) {
// Did not find a child to receive the event.
// Assign the pointer to the least recently added target.
// 没有找到一个孩子接收这个事件
// 将指针分配到最近添加的那个目标
// 把目标链表中第一个触摸目标 mFirstTouchTarget 赋给触摸目标 newTouchTarget
newTouchTarget = mFirstTouchTarget;
// while 循环,条件:触摸目标 newTouchTarget 的下一个触摸目标不为 null
while (newTouchTarget.next != null) {
// 触摸目标 newTouchTarget 赋值为其下一个对象
newTouchTarget = newTouchTarget.next;
}
newTouchTarget.pointerIdBits |= idBitsToAssign;
}
}
}
// Dispatch to touch targets.
// 发送到触摸目标
// 拦截事件或调度转换触摸事件返回 false,事件由 ViewGroup 自己处理
if (mFirstTouchTarget == null) {
// No touch targets so treat this as an ordinary view.
// 没有触摸目标,所以把它(ViewGroup)当作一个普通的 view 看待
// ------------------》关键:ViewGroup 自己处理或其子控件处理事件《------------------
// 此处为 ViewGroup 自己处理处理事件
handled = dispatchTransformedTouchEvent(ev, canceled, null,
TouchTarget.ALL_POINTER_IDS);
} else { // 目标链表中第一个触摸目标 mFirstTouchTarget 不为空,代表不拦截,事件由子 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;
// 已调度到新的触摸目标 alreadyDispatchedToNewTouchTarget 默认为 false,此时为 false,不拦截时才会被赋值为 true
if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
handled = true;
} else {
final boolean cancelChild = resetCancelNextUpFlag(target.child)
|| intercepted;
// ------------------》关键:ViewGroup 自己处理或其子控件处理事件《------------------
// 此处为 ViewGroup 的子控件处理事件
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;
}
总结:
ViewGroup#dispatchTouchEvent() 每一轮事件从处理 DOWN 开始,会重置所有触摸状态,每次都会判断是否需要拦截 DOWN 事件
① 如果不拦截,会执行 addTouchTarget() 方法对 mFirstTouchTarget 进行赋值,之后通过 dispatchTransformedTouchEvent() 方法传递触摸事件
② 如果拦截,直接通过 dispatchTransformedTouchEvent() 方法传递触摸事件,其中会调用 super.dispatchTouchEvent()
ViewGroup 拦截事件,之后的 MOVE 和 UP 事件不再判断是否拦截,同一序列中的其他事件将直接交给 super.dispatchTouchEvent()
四、View 对事件的处理
View#dispatchTouchEvent():
// 1.先调用 onTouch()
if (li != null && li.mOnTouchListener != null
&& (mViewFlags & ENABLED_MASK) == ENABLED
&& li.mOnTouchListener.onTouch(this, event)) {
// 如果 onTouch() 返回 true,则事件被消费
result = true;
}
// 2.再调用 onTouchEvent()
if (!result && onTouchEvent(event)) {
// 如果 onTouchEvent() 返回 ture,则事件被消费
result = true;
}
// 在 onTouchEvent() 中调用 onClick()
onTouchEvent() -> performClick() -> li.mOnClickListener.onClick(this);