版权声明:本文为博主原创文章,未经博主允许不得转载
Github:github.com/AnliaLee
大家要是看到有错误的地方或者有啥好的建议,欢迎留言评论
前言
本篇博客我们将由浅入深地讲解Android的事件分发机制,讲解的顺序为分发流程概括 → 源码分析,大家可以根据需要查阅相应的部分。最后,感谢前辈们将自己的知识总结和经验分享出来,参考资料已在下方贴出
参考资料
Android开发艺术探索
Android进阶之光
Android显示框架:Android应用视图的载体View
Android View 事件分发机制 源码解析(ViewGroup篇)
下面我们就正式开始讲解吧
事件分发机制简介
为什么需要事件分发机制
Android上的View是树形结构的,View有可能会重叠在一起,如果我们点击的位置有多个View都可以处理这次事件时,那事件该交给谁去处理呢?为了解决这个问题,便有了事件分发机制,相应地也就有了事件分发、拦截和消费的概念
事件分发流程梳理
在深入分析源码之前,我们先了解其中一些基本的类和方法,以及它们在事件分发机制中扮演的角色:
- MotionEvent
此对象是与用户触摸相关的时间序列,从用户首次触摸屏幕(ACTION_DOWN)开始,经历手指在屏幕表面的移动(ACTION_DOWN),一直到手指离开屏幕(ACTION_UP)时结束,每一次动作事件都会创建MotionEvent对象,这个过程可以概括为DOWN → MOVE … MOVE → UP(过程中会产生多个MOVE事件)。另外,MotionEvent中还记录许多信息,例如触摸的位置,指压的范围,按下的时间等等 - dispatchTouchEvent
分发事件的方法,ViewGroup和View的dispatchTouchEvent扮演的角色是不同的,在ViewGroup中主要负责遍历子View将事件分发下去,而在View中则负责调用相应的方法来消费这个事件 - onInterceptTouchEvent
在ViewGroup.dispatchTouchEvent中调用,负责拦截事件,使得事件不再分发给子View而由ViewGroup自己处理(注意,仅ViewGroup拥有该方法,View是没有的) - onTouchEvent
在View.dispatchTouchEvent中调用,负责具体处理事件,View是否消费事件由该方法的返回值决定,若为true,则代表View要消费事件,为false则不消费
通过代码来讲解分发的逻辑我觉得比写一大段文字描述更让人容易理解。下面我们通过精简源码得到的伪代码来梳理一下事件分发的流程,看看上述角色之间到底是如何运作的
//ViewGroup
public boolean dispatchTouchEvent(MotionEvent ev) {
boolean result = false;
View target = null;
//ViewGroup拦截了这次事件
if(onInterceptTouchEvent(ev)){
//ViewGroup继承自View
//这里由自己父类(View)的dispatchTouchEvent方法来处理这次事件
result = super.dispatchTouchEvent(ev);
}else{
final View[] children = mChildren;
for (int i = childrenCount - 1; i >= 0; i--) {
//有子View消费了这次事件
if(children[i].dispatchTouchEvent(ev)){
target = children[i];
result = true;
return result;//若找到了消费此次事件的子View那么就不会再继续分发事件了
}
}
}
//没有合适的子View消费这次事件
if(target == null){
//事件就让ViewGroup自己来处理(和之前设置拦截一样将事件交由父类的dispatchTouchEvent方法处理)
result = super.dispatchTouchEvent(ev);
}
return result;
}
public boolean onInterceptTouchEvent(MotionEvent ev) {
return false;//默认返回false
}
//View
public boolean dispatchTouchEvent(MotionEvent event) {
boolean result = false;
//先看看有无设置OnTouchListener,且onTouch是否返回true
if (mOnTouchListener != null && mOnTouchListener.onTouch(this, event)) {
result = true;
}
//onTouchEvent的优先级在OnTouchListener.onTouch之后
if (!result && onTouchEvent(event)) {
result = true;
}
return result;
}
public boolean onTouchEvent(MotionEvent event) {
//View的CLICKABLE和LONG_CLICKABLE两个状态只要有一个为true,则View消费此事件
//LONG_CLICKABLE默认为false,而CLICKABLE的默认值和View的类型有关,例如Button的为true,TextView的则为false
//setOnClickListener会将CLICKABLE设为true(setOnLongClickListener同理)
//以CLICKABLE为例
if(CLICKABLE){
performClick();
return true;
}
return false;
}
public boolean performClick(){
boolean result = false;
if(mOnClickListener!=null){
//performClick中调用了onClick方法
mOnClickListener.onClick(this);
result = true;
}
return result;
}
如果只是想简单了解事件分发的过程,那么看到这也就足够了。如果想深入到源码(Android 8.0版本),那么我们就继续往下看吧~
源码解析
事件会先传递到Activity,并调用Activity.dispatchTouchEvent(有关事件是如何传递到Activity的请看这篇博客:Android中MotionEvent的来源和ViewRootImpl)
//Activity.java
public boolean dispatchTouchEvent(MotionEvent ev) {
...
//事件继续分发,由PhoneWindow的superDispatchTouchEvent方法进行处理
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
//如果事件没有被Activity下面任何一个视图消费,那么就会交由Activity自己的onTouchEvent方法去处理
return onTouchEvent(ev);
}
Activity将事件交给了Window.superDispatchTouchEvent方法去处理,这是一个抽象方法,翻查Activity源码后得知Window对象的实现类是PhoneWindow,所以事件其实是分发给了PhoneWindow。我们继续跟踪下去
//PhoneWindow.java
private DecorView mDecor;
public boolean superDispatchTouchEvent(MotionEvent event) {
return mDecor.superDispatchTouchEvent(event);
}
DecorView是所有View的根View,其继承自FrameLayout
public class DecorView extends FrameLayout implements RootViewSurfaceTaker, WindowCallbacks
FrameLayout是ViewGroup的子类,所以接下来我们开始详细分析ViewGroup的dispatchTouchEvent
//ViewGroup.java
private TouchTarget mFirstTouchTarget;//触摸目标链接列表中的第一个触摸目标
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,都会重置成初始状态
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);//初始化mFirstTouchTarget并把mFirstTouchTarget所在的链表清空
resetTouchState();//重置所有触摸状态以迎接新的事件到来
}
final boolean intercepted;//是否拦截事件
//ViewGroup在两种情况下会调用onInterceptTouchEvent(注意只有这里会调用onInterceptTouchEvent)
//一是接收到ACTION_DOWN
//二是mFirstTouchTarget!=null,即有子View表示要消费此事件
//如果事件在ACTION_DOWN到来时就已经成功拦截(onInterceptTouchEvent返回true)
//那么mFirstTouchTarget肯定也为null
//则当接收到ACTION_MOVE或ACTION_UP时,由于上述两个条件都不符合,也就不会再调用onInterceptTouchEvent了
//这也说明了onInterceptTouchEvent并不是每次都会被调用的
if (actionMasked == MotionEvent.ACTION_DOWN
|| mFirstTouchTarget != null) {
//mGroupFlags和FLAG_DISALLOW_INTERCEPT标志位进行比对,判断子View是否阻止ViewGroup拦截事件
//子View可以使用requestDisallowInterceptTouchEvent方法设置FLAG_DISALLOW_INTERCEPT标志位
//requestDisallowInterceptTouchEvent设为true即代表子View要阻止ViewGroup拦截事件
//由于接收ACTION_DOWN会重置状态,因此requestDisallowInterceptTouchEvent对于DOWN来说是无效的
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
if (!disallowIntercept) {
//调用onInterceptTouchEvent方法对事件进行拦截
//拦截结果取决于该方法的返回值,若为true则代表ViewGroup要拦截此次事件
intercepted = onInterceptTouchEvent(ev);
ev.setAction(action); //恢复事件的动作类型,防止被更改(这里这么写的原因有待考察...)
} else {
intercepted = false;
}
} else {
//若没有任何子View消费此事件,事件会交由ViewGroup处理,相当于ViewGroup拦截了这次事件
intercepted = true;
}
//如果ViewGroup拦截了事件或者有子View消费事件,都会按照正常的流程去派发事件
//setTargetAccessibilityFocus设置为false的原因是事件的目标如果是可访问的焦点,会影响事件的派发流程
//具体原因可以继续往下看源码
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;
//若事件没有被取消也没有被ViewGroup拦截,进入if语句
if (!canceled && !intercepted) {
//如果事件的目标是可访问的焦点时,就会去查找具有可访问焦点的View
//如果找到的子View不处理事件,则会按照正常的派发流程将事件派发给所有子View
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<View> preorderedList = buildTouchDispatchChildList();
final boolean customOrder = preorderedList == null
&& isChildrenDrawingOrderEnabled();
final View[] children = mChildren;
//此处开始倒序遍历子View分发事件(有关遍历顺序的示例请看附录一)
for (int i = childrenCount - 1; i >= 0; i--) {
final int childIndex = getAndVerifyPreorderedIndex(
childrenCount, i, customOrder);
final View child = getAndVerifyPreorderedView(
preorderedList, children, childIndex);
//如果当前子View具有可访问的焦点时,会让该子View优先获得这次事件
if (childWithAccessibilityFocus != null) {
if (childWithAccessibilityFocus != child) {
continue;
}
childWithAccessibilityFocus = null;
i = childrenCount - 1;
}
//canViewReceivePointerEvents:判断子View是否正常显示(VISIBLE)或者子View是否在播放动画
//isTransformedTouchPointInView:判断触摸点位置是否在子View范围内
if (!canViewReceivePointerEvents(child)
|| !isTransformedTouchPointInView(x, y, child, null)) {
ev.setTargetAccessibilityFocus(false);
//由判断条件可知如果在子View原有的位置上没有看到子View,同时子View也不是因为动画而离开原来的位置
//那么这丫的肯定是隐藏了,因此不符合事件消费的条件,所以执行continue跳过
//如果用户触摸的位置不在子View的范围内,肯定也不符合事件消费的条件,同样执行continue跳过
continue;
//那么为什么要这样判断呢?其目的在于确保了子View即使是因为动画(例如位移动画)的原因离开了原来的位置
//子View也可以正常分发触摸了原范围内的事件
//这也正是子View执行位移动画后点击位置为什么没有跟随子View来到新位置的原因
}
//getTouchTarget:查找当前子View是否在mFirstTouchTarget所在的触摸目标链表中
//若存在则返回这个target,否则返回null
//这里的判断主要用于多点触控的情况,例如手指触摸某个子View触发了ACTION_DOWN
//这时另一根手指也放在这个视图上触发了ACTION_POINTER_DOWN
//此时就需要通过在链表中查找当前子View的结果来判断两根手指触摸的是否为同一个View
newTouchTarget = getTouchTarget(child);
if (newTouchTarget != null) {
//newTouchTarget不为null则代表触摸了同一个子View
//则将触摸点Id复制给新的TouchTarget对象,并执行break跳出遍历
newTouchTarget.pointerIdBits |= idBitsToAssign;
break;
}
resetCancelNextUpFlag(child);
//将事件分发给子View
//dispatchTransformedTouchEvent方法中调用了child.dispatchTouchEvent
if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
//如果返回值为true,说明子View消费了事件
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加入到触摸链表中
//且addTouchTarget方法中会对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);
}
if (preorderedList != null) preorderedList.clear();
}
//当mFirstTouchTarget!=null时,newTouchTarget==null
//则意味着没有找到新的可以消费事件的子View,那就找最近消费事件的子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调用super.dispatchTouchEvent自己处理事件
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;
while (target != null) {
final TouchTarget next = target.next;
//根据标志判断事件是否已经确认分发过了,如果是则设置处理标志位handled为true
//此处做这样的判断是因为虽然在ACTION_DOWN到来时已经确认了有子View会消费事件,但不排除用户会在后续的动作(例如MOVE)中对事件进行拦截
//如果拦截了,会把之前加入到触摸目标链表中的target清除掉,并将mFirstTouchTarget设为null
//那么下一次动作事件到来时,就会进入if (mFirstTouchTarget == null)中,让ViewGroup自己去处理事件,用户拦截的目的也就达到了
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;
}
}
// 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的onInterceptTouchEvent的代码很简单
//ViewGroup.java
public boolean onInterceptTouchEvent(MotionEvent ev) {
//这里主要是关于鼠标或者触控笔方面的判断的,暂且略过
if (ev.isFromSource(InputDevice.SOURCE_MOUSE)
&& ev.getAction() == MotionEvent.ACTION_DOWN
&& ev.isButtonPressed(MotionEvent.BUTTON_PRIMARY)
&& isOnScrollbarThumb(ev.getX(), ev.getY())) {
return true;
}
//默认返回false,因此设置拦截事件需重写onInterceptTouchEvent并返回true
return false;
}
由于在ViewGroup中并没有重写onTouchEvent(有的ViewGroup子孙类会重写这个方法,例如ScrollView),所以ViewGroup部分到这就结束了。接下来按照事件分发的流程我们继续分析View的dispatchTouchEvent方法
//View.java
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
//这里和NestedScrolling嵌套滑动机制有关,暂略
stopNestedScroll();
}
if (onFilterTouchEventForSecurity(event)) {
if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
result = true;
}
//noinspection SimplifiableIfStatement
ListenerInfo li = mListenerInfo;
//如果设置了OnTouchListener且OnTouchListener.onTouch返回true
//那么事件就交给onTouch去处理
if (li != null && li.mOnTouchListener != null
&& (mViewFlags & ENABLED_MASK) == ENABLED
&& li.mOnTouchListener.onTouch(this, event)) {
result = true;
}
//从这里就可以看出来onTouch的优先级高于onTouchEvent
//当onTouch没有消费此事件时,就会由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;
}
代码很简单,View的dispatchTouchEvent方法主要是确定事件是交给onTouch还是onTouchEvent去处理
public interface OnTouchListener {
boolean onTouch(View v, MotionEvent event);
}
OnTouchListener是一个接口,需要我们去重写onTouch方法,这里就不多赘述了。接着看onTouchEvent的源码,我们只了解和事件分发有关的部分
//View.java
public boolean onTouchEvent(MotionEvent event) {
...
final int action = event.getAction();
//setOnClickListener会设置CLICKABLE属性
//setOnLongClickListener会设置LONG_CLICKABLE属性
//只要CLICKABLE或LONG_CLICKABLE为true,onTouchEvent就会返回true,即View消费此事件
final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE
|| (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
|| (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
//View的disable属性对onTouchEvent方法的返回值没有影响
if ((viewFlags & ENABLED_MASK) == DISABLED) {
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.
return clickable;
}
...
//Android 8.0多了关于鼠标悬浮显示工具提示的判断(TOOLTIP),这里我们就略过不赘述了
if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
switch (action) {
case MotionEvent.ACTION_UP:
...
if (mPerformClick == null) {
mPerformClick = new PerformClick();
}
//在performClick方法中会判断用户是否设置了OnClickListener
//如果有就会调用OnClickListener.onClick
if (!post(mPerformClick)) {
performClick();
}
...
break;
case MotionEvent.ACTION_DOWN:
...
break;
case MotionEvent.ACTION_CANCEL:
...
break;
case MotionEvent.ACTION_MOVE:
...
break;
}
return true;
}
return false;
}
public boolean performClick() {
final boolean result;
final ListenerInfo li = mListenerInfo;
if (li != null && li.mOnClickListener != null) {
playSoundEffect(SoundEffectConstants.CLICK);
li.mOnClickListener.onClick(this);
result = true;
} else {
result = false;
}
...
return result;
}
public interface OnClickListener {
void onClick(View v);
}
事件分发机制的源码到这就分析完毕了,下一篇博客我们将运用从解析事件分发源码中学到的知识来解决一些常见的滑动冲突问题
最后还是惯例的求赞环节:如果觉得博主写得还不错麻烦点个赞,你们的支持是我最大的动力~
附录一:子View遍历顺序示例
我们假设当前Activity中View的分布与层叠关系如下图所示
其中这5个View组成这样一个ViewGroup与View的树形关系图
布局文件的代码大概是这样的
<RelativeLayout
android:id="@+id/view1">
<View
android:id="@+id/view2"/>
<RelativeLayout
android:id="@+id/view3">
<View
android:id="@+id/view4"/>
<View
android:id="@+id/view5"/>
</RelativeLayout>
</RelativeLayout>
那么以根view1为起点,View事件分发的顺序为① - ③ - ⑤ - ④ - ②,也就是说在事件分发机制中,ViewGroup遍历它的直接子View是倒序的