一 前言
上一篇从源码角度梳理了一下View的工作原理,其中主要分析了View是如何一步步显示给用户的,本篇主要分析View与用户交互的事件体系。
二 View事件体系
对于View的事件体系,我看了很多相关文章,结合源码梳理一下整个View的事件分发,拦截,消费流程,首先介绍一下关键概念,View事件分发的对象——MotionEvent
2.1 MotionEvent——触摸事件
MotionEvent包括了Android系统的所有输入操作,主要有以下三种类型:
- ACTION_DOWN--------手指初次触摸屏幕是触发;
- ACTION_MOVE--------手指在屏幕上滑动时,多次触发;
- ACTION_UP-------------手指离开手机屏幕时,触发;
- ACTION_CANCLE-----事件被上层拦截时,触发;
- ACTION_OUTSIDE----手指不在控件区域范围没,触发;
可以想想我们平常的一些手机触控操作,都是由上面几个输入操作类型组成的
点击事件:ACTION_DOWM---ACTION_UP
双击事件:ACTION_DOWN---ACTION_UP---ACTION_DOWN---ACTION_UP
滑动事件:ACTION_DOWN---ACTION_MOVE---ACTION_MOVE---......
ACTION_UP
2.2 事件分发机制
上一篇梳理了View树的结构,如下图:
View ViewGroup,DecorView有可能是层级关系,当手持触摸屏幕时,到底那个控件触发消费这个事件对象?Android系统采用了非常巧妙的责任链模式解决这个问题。下面说说View事件的分发机制:
(1)当手持按下时,MotionEvent会传递到Activity的dispatchTouchEvent方法,源码如下:
public boolean dispatchTouchEvent(MotionEvent ev) {
//手指下按时,就是ACTION_DOWN
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
onUserInteraction();
}
//a. 调用phoneWindow的dispatchTouchEvent方法
如果phoneWindow的dispatchTouchEvent返回true,就消费事件,
不在往下传递
否则进入自身的onTouchEvent方法,进行事件消费;
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
}
下面继续看Activity的onTouchEvent方法,一般情况下,这个事件不会触发,因为activity的包含的子View会消费掉事件,但是如果开发者自己做了事件处理,或者Dialog(其实它是Window的一种表现形式)的外部点击,会触发这个事件。
/**
* Called when a touch screen event was not handled by any of the views
* under it. This is most useful to process touch events that happen
* outside of your window bounds, where there is no view to receive it.
*
* @param event The touch screen event being processed.
*
* @return Return true if you have consumed the event, false if you haven't.
* The default implementation always returns false.
*/
public boolean onTouchEvent(MotionEvent event) {
//a1 消费这个事件
if (mWindow.shouldCloseOnTouch(this, event)) {
finish();
return true;
}
return false;
}
(2)接着源码a部分,调用PhoneWindow的dispatchTouchEvent方法,源码如下:
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
//b.直接调用了DecorView的dispatchTouchEvent方法
return mDecor.superDispatchTouchEvent(event);
}
(3) 接着源码b部分,调用DecorView的superDispatchTouchEvent方法
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
//c. 直接调用DecorView父类的dispatchTouchEvent
final Window.Callback cb = mWindow.getCallback();
return cb != null && !mWindow.isDestroyed() && mFeatureId < 0
? cb.dispatchTouchEvent(ev) : super.dispatchTouchEvent(ev);
}
(4)由于DecorView继承FrameLayout,而FrameLayout继承ViewGroup,所以接下来直接看ViewGroup的dispatchTouchEvent方法:
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
......
boolean handled = false;
//d1.是否要分发该触摸事件
if (onFilterTouchEventForSecurity(ev)) {
final int action = ev.getAction();
final int actionMasked = action & MotionEvent.ACTION_MASK;
// Handle an initial down.
//d2.判断是否为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);
resetTouchState();
}
// Check for interception.
final boolean intercepted;
//d3.检查当前ViewGroup是否想要拦截触摸事件
// 是的话,设置intercepted为true;否则为false
if (actionMasked == MotionEvent.ACTION_DOWN
|| mFirstTouchTarget != null) {
//d4.ViewGroup是否设置了FLAG_DISALLOW_INTERCEPT标记位
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
if (!disallowIntercept) {
//d5.拦截事件消费,默认不拦截返回false
intercepted = onInterceptTouchEvent(ev);
ev.setAction(action); // restore action in case it was changed
} else {
//设置是否拦截为false
intercepted = false;
}
} else {
intercepted = true;
}
if (intercepted || mFirstTouchTarget != null) {
ev.setTargetAccessibilityFocus(false);
}
// Check for cancelation.
//检查事件是否为ACTION_CANCE事件
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) {
//如果事件不是取消事件并且ViewGroup不会拦截这个事件
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();
//d6.遍历ViewGroup的子View,分发触摸事件
final View[] children = mChildren;
for (int i = childrenCount - 1; i >= 0; i--) {
final int childIndex = getAndVerifyPreorderedIndex(
childrenCount, i, customOrder);
final View child = getAndVerifyPreorderedView(
preorderedList, children, childIndex);
if (childWithAccessibilityFocus != null) {
if (childWithAccessibilityFocus != child) {
continue;
}
childWithAccessibilityFocus = null;
i = childrenCount - 1;
}
if (!canViewReceivePointerEvents(child)
|| !isTransformedTouchPointInView(x, y, child, null)) {
ev.setTargetAccessibilityFocus(false);
continue;
}
newTouchTarget = getTouchTarget(child);
if (newTouchTarget != null) {
newTouchTarget.pointerIdBits |= idBitsToAssign;
break;
}
resetCancelNextUpFlag(child);
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 = 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();
}
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) {
// No touch targets so treat this as an ordinary view.
//e 调用父类或者子View的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;
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.
......
}
.....
}
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) {
//e1.如果没有子View调用父类dispatchTouchEvent方法,这里其实进入了a1方法;
handled = super.dispatchTouchEvent(event);
} else {
//e2.如果有子View,向下继续分发事件;
handled = child.dispatchTouchEvent(event);
}
event.setAction(oldAction);
return handled;
}
}
(5)从源码d5看看ViewGroup的拦截事件
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
return false;
}
(6)从源码e1看看View的dispatchTouchEvent方法:
public boolean dispatchTouchEvent(MotionEvent event) {
// 判断当前View是否为事件的AccessibilityFocus
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;
//判断OnTouchListener是否为空,否则调用其OnTouch方法
if (li != null && li.mOnTouchListener != null
&& (mViewFlags & ENABLED_MASK) == ENABLED
&& li.mOnTouchListener.onTouch(this, event))
result = true;
}
//f.调用View的onTouchEvent方法
if (!result && onTouchEvent(event)) {
result = true;
}
}
if (!result && mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
}
......
}
(7)从源码f调用onTouchEvent方法,当事件从Activit分发到ViewGroup,再分发大View的时候,一般都会在这里消费。
public boolean onTouchEvent(MotionEvent event) {
//获取触摸事件相对父View的坐标
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;
//f1.1判断是否为Disable状态
if ((viewFlags & ENABLED_MASK) == DISABLED) {
if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
//f1.2 判断是否可点击,且为长按状态
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;
}
//f2 是否设置了TouchDelegate
if (mTouchDelegate != null) {
if (mTouchDelegate.onTouchEvent(event)) {
return true;
}
}
//f3 是否可点击或者长按
if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
switch (action) {
case MotionEvent.ACTION_UP:
//f4.手指离开屏幕时,消费事件
mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
if ((viewFlags & TOOLTIP) == TOOLTIP) {
handleTooltipUp();
}
//f4.1 view是否可以点击
if (!clickable) {
removeTapCallback();
removeLongPressCallback();
mInContextButtonPress = false;
mHasPerformedLongPress = false;
mIgnoreNextUpEvent = false;
break;
}
boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
//4.2 View是否可以按
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);
}
//f4.3是否执行了长按操作
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)) {
performClick();
}
}
}
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:
//f5.手指首次触摸手机手机屏幕时,消费事件
......
break;
case MotionEvent.ACTION_CANCEL:
//f6.事件被上层拦截时触发
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);
}
// Be lenient about moving outside of buttons
if (!pointInView(x, y, mTouchSlop)) {
// Outside button
// Remove any future long press/tap checks
removeTapCallback();
removeLongPressCallback();
if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
setPressed(false);
}
mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
}
break;
}
return true;
}
return false;
}
2.3 事件传递规则
从上面的源码分析,可以看出当点击一个View时,事件的传递流程如下:
Activity---PhoneWindow---DecorView---ViewGroup---View
但是当最底层的View没有消费事件时,事件的消费流程如下:
View---ViewGroup---DecorView---PhoneWindow---Activity
事件分发的方法主要有dispatchTouchEvent,onInterceptTouchEvent,onTouchEvent三个事件,其中Activity和View是没有onInterceptTouchEvent事件的,原因很简单:
Activity作为事件分发的起始端,如果 Activity 拦截了事件会就导致整个屏幕都无法响应事件;
View作为事件传递的最底层,要么消费,要么回传上层消费,没有必要拦截。
2.4 事件流程解析图
根据上面源码分析的步骤小标记画一张事件分发和消费的流程图。
几点结论:
(1)黑色箭头代表View的分发流程,青色箭头代表最末端View不消费Event事件时,向上回调,消费流程;
(2)前面说MotionEvent时,提到过这个点击view时,其实是一连串的ACTION,每个ACTION会走上图的流程,当ACTION_DOWN被VIEW或者VIEWGROUP拦截时,也就是说返回false时,紧跟其后的事件序列也不会向下分发了,都叫给该View处理了。
(3)ViewGroup默认不拦截任何事件。
参考文章
[1] 安卓自定义View进阶-事件分发机制原理
[2]《Android 开发艺术探索》
由于能力有限,有的方面可能理解不当,后期会根据情况随时调整。