深刻理解事件分发对解决事件冲突上有着非常大的帮助,安卓事件分发机制也是需要重点掌握。很多效果实现都必须配合手势来实现。涉及手势必然会有事件,事件的分发和消费都应该十分清楚。
首先我们可以想象一下,我们手指点击的地方是 Activity,根据之前的一篇文章讲过,setContentView 设置的布局文件,最终是由 PhoneWindow 内部维护的 DecorView 来进行加载工作的。所以我们能看到的 view 必然是在 Activity 中,那是不是点击的事件必然也是从 Activity 中开始分发的? 分发事件翻译成英文的大概意思就是 dispatchEvent。 那么直接到 Activity 中去查找是否有相似名称的方法,找到了一个 dispatchTouchEvent 方法,这个方法就是我们要找的。 代码如下:
/**
* Called to process touch screen events. You can override this to
* intercept all touch screen events before they are dispatched to the
* window. Be sure to call this implementation for touch screen events
* that should be handled normally.
*
* @param ev The touch screen event.
*
* @return boolean Return true if this event was consumed.
*/
public boolean dispatchTouchEvent(MotionEvent ev) {
// 检查手势按下
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
// 其他的一些事件,比如悬浮球、屏幕熄屏幕点亮事件处理.
onUserInteraction();
}
// 交给 PhoneWindow 的 superDispatchTouchEvent
// 至于为什么是 PhonwWindow, 请看我的布局文件加载过程分析文章.
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
// 如果所有的视图都没有处理事件,事件回传给 Activity 的 onTouchEvent
return onTouchEvent(ev);
}
这里我将它的英文注释也给出,根据注释知道,如果重载这个方法返回 true 的话,所有的事件都不会传递下去。
上面的方法最终会到 ViewGroup 中, 为什么呢?请阅读我的布局加载文件分析文章。请看 ViewGroup 的 dispatchTouchEvent 方法如下:
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
.... 省略部分代码
boolean handled = false;
// 有效的手势按下会返回 true, 即当前窗口是不是被遮挡住
if (onFilterTouchEventForSecurity(ev)) {
final int action = ev.getAction();
final int actionMasked = action & MotionEvent.ACTION_MASK;
// Handle an initial 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.
// 新的事件产生,清空老的事件产生的数据,响应新的事件
// 首先重置 MotionEvent,其次是将维护 TouchTarget 的链表清空
cancelAndClearTouchTargets(ev);
// 将 mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;
resetTouchState();
}
// Check for interception.
final boolean intercepted;
// 已经确定了点击的 view 后,这个值 mFirstTouchTarget 不为空。
if (actionMasked == MotionEvent.ACTION_DOWN
|| mFirstTouchTarget != null) {
// 如果是 down 事件,这个返回值一定为 false, 因为前面调用了 resetTouchState() 方法
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
if (!disallowIntercept) {
// 如果是 ViewGroup 的子类,可以重写此方法来拦截事件。返回 true 拦截。
intercepted = onInterceptTouchEvent(ev);
ev.setAction(action); // restore action in case it was changed
} else {
// 如果不是 down 事件且 mFirstTouchTarget 不为空
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 split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;
TouchTarget newTouchTarget = null;
boolean alreadyDispatchedToNewTouchTarget = false;
// 事件未被 ViewGroup 拦截,子 view 有机会处理事件
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) {
// 处理多手指按下的事件
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);
// 当前 ViewGroup 的子 view 个数.
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.
// 这个方法对 view 响应事件的顺序进行调整,根据 z 轴的值,这也很好理解
// z 轴的值越大,说明 view 处于最顶层,应当优先处理事件.
final ArrayList<View> preorderedList = buildTouchDispatchChildList();
final boolean customOrder = preorderedList == null
&& isChildrenDrawingOrderEnabled();
// 当前 ViewGroup 的子 view
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);
..... 省略部分代码
// 这里的第一个方法是判断,当前的 view 是否有动画正在执行,是否可见
// 第二个方法检查当前按下的点是否在 view 上, 如果没在就跳过。
if (!canViewReceivePointerEvents(child)
|| !isTransformedTouchPointInView(x, y, child, null)) {
ev.setTargetAccessibilityFocus(false);
continue;
}
// 第一个事件来的时候,newTouchTarget 为空。但是如果按下后移动或其他手指按下 newTouchTarget 不为空 ,就会跳过循环。
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);
// 这个方法非常关键,将事件向下分发的地方。如果是 view 则调用
// View 的dispatchTouchEvent, 如果是 ViewGroup 则又递归查找当前 ViewGroup 下的所有 view
if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
..... 省略部分代码
// 事件一旦被某个 view 消费,这里就会将这个 view 存放到链表的头节点,为了让后续的所有事件都交给它来处理
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();
}
..... 省略部分代码
}
}
// Dispatch to touch targets.
// 如果没有 view 消费,最终会调用本身的 onTouchEvent
if (mFirstTouchTarget == null) {
// No touch targets so treat this as an ordinary view.
// 根据返回值,将事件回传。
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;
// 如果是新的事件被处理,返回 true。说明有事件已经被 view 消费啦
if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
handled = true;
} else {
// 当前的 view 是否设置了抬起标示,如果设置了,说明当前的 view 事件即将结束。
final boolean cancelChild = resetCancelNextUpFlag(target.child)
|| intercepted;
// 将后续事件分发到 cancelChild
if (dispatchTransformedTouchEvent(ev, cancelChild,
target.child, target.pointerIdBits)) {
handled = true;
}
// 当前的 child 事件处理结束,将其回收
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);
}
// 如果 handled 为 true, 就会回到最终 Activity 的 dispatchTouchEvent , 条件判断不成立,而执行 Activity onTouchEvent 方法。
return handled;
}
关键代码都有注释,再次梳理一下流程,首先 ACTION_DOWN 事件发生,会先重置 TouchTargets,重置 mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT; 接着当前容器是否重载 onInterceptTouchEvent 方法并返回 true, 如果返回 false 倒序遍历该容器下的所有子 view, 我们在布局中写的控件,一般情况下后面的显示在最上面,除非设置了 z 轴方向的值,这个方法 buildTouchDispatchChildList() 就是将 z 轴越到的进行排序。然后取出一个子 view 并判断它是否可见,是否执行动画,以及是否被点击到。就会进入最为关键的方法 dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,View child, int desiredPointerIdBits), 这个方法内部根据传入进来的 child 是否为空,将事件由本身的 dispatchTouchEvent, 还是父容器的 dispatchTouchEvent。如果 child 消费了事件返回 true, mFirstTouchTarget 就会指向当前 child 的 target。接着就可以继续响应后续的事件。
OK,上面分析了 ViewGroup 代码中一长串的代码,接下里就是看 view 的 dispatchTouchEvent 做了什么。
public boolean dispatchTouchEvent(MotionEvent event) {
...... 省略部分代码
if (onFilterTouchEventForSecurity(event)) {
if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
result = true;
}
//noinspection SimplifiableIfStatement
// 我们平时给 view 设置的 setOnClickListener 就是通过它来维护的。
// li.mOnTouchListener.onTouch(this, event) 这个比较关键啦,如果我们给 view setOnTouchListener 并且返回了 true, 那么 onTouchEvent 就不被调用
ListenerInfo li = mListenerInfo;
if (li != null && li.mOnTouchListener != null
&& (mViewFlags & ENABLED_MASK) == ENABLED
&& li.mOnTouchListener.onTouch(this, event)) {
result = true;
}
// 如果上面为 true,onTouchEvent 不被调用
if (!result && onTouchEvent(event)) {
result = true;
}
}
...... 省略部分代码
return result;
}
来看 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();
// view 是否可以点击。
final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE
|| (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
|| (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
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;
}
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);
}
// 因为点击事件和长按事件只是通过按下的事件来区分的,如果 mHasPerformedLongPress 为 true 表示长按发生
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();
}
//调用 performClickInternal 方法,内部调用设置的点击监听器 li.mOnClickListener.onClick(this);
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(0, x, y);
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);
// 检查长按事件,如果事件大于 500 毫秒就会触发 performLongClick, 内部调用了performLongClickInternal,然后调用 li.mOnLongClickListener.onLongClick(View.this)
checkForLongClick(0, x, y);
}
break;
case MotionEvent.ACTION_CANCEL:
......
case MotionEvent.ACTION_MOVE:
........
}
return true;
}
return false;
}
再次梳理 View 的 dispatchTouchEvent , 首先检查 View 是否设置 setOnTouchListener 并返回 true。 如果没有设置则调用 View 的 onTouchEvent。 在这个方法里处理 view 点击和长按处理。
说明一个顺序: View 的setOnTouchListener > onTouchEvent, 长按事件 > 点击事件。
最后来一张流程分析图结束源码分析的过程。
