View的事件分发机制是Android中的一个难点,也是非常重要的知识点,充分理解和掌握事件分发机制有助于我们在自定义view的过程中更好地设计和解决事件相关问题。下面我们通过源码的角度去分析一下Android是怎么处理view事件的。
一个事件(比如手指按下屏幕的down事件)首先传递到activity,它的大致传递顺序是Activity->Window->View,即先从activity的dispatchTouchEvent开始进行事件分发,具体是由activity内部的Window来完成的,Window再将事件传递给decor view,decor view是顶级view的父容器,顶级view就是我们在onCreate方法中的setContentView所设置的view,一般是一个ViewGroup。到达顶级view以后,假设我们的顶级view是一个ViewGroup,那么此时就会调用ViewGroup的dispatchTouchEvent方法将事件分发下去。因为有一个很重要的地方,就是ViewGroup的dispatchTouchEvent方法和view的dispatchTouchEvent方法处理事件的机制是完全不一样的,所以我们这里先从ViewGroup的dispatchTouchEvent方法开始,进行事件分发的分析。
首先我们来看看ViewGroup的dispatchTouchEvent方法源码,代码有点长,我抽取关键代码贴出来,如下:
public boolean dispatchTouchEvent(MotionEvent ev) {
// 省略部分代码..............
// Check for interception.
// mFirstTouchTarget 代表是否有子view消费了事件
final boolean intercepted; //是否拦截事件
if (actionMasked == MotionEvent.ACTION_DOWN
|| mFirstTouchTarget != null) {
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
if (!disallowIntercept) {
//调用了拦截事件的方法,返回Boolean代表是否拦截事件,ViewGroup一般默认不拦截事件
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;
}
// 省略部分代码...................
//下面是循环遍历ViewGroup的子view,逐一询问子view是否要消费事件
final int childrenCount = mChildrenCount; //子view个数
//
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);
// If there is a view that has accessibility focus we want it
// to get the event first and if not handled we will perform a
// normal dispatch. We may do a double iteration but this is
// safer given the timeframe.
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) {
// 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);
// 方法dispatchTransformedTouchEvent是将事件分发给当前child,返回值代表child是否消费了事件,
//如果child为null,就会调用ViewGroup父类view的dispatchTouchEvent方法,代表当前ViewGroup是
//否消费此事件,因为这里child不为null,所以这里返回的是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 赋值,就代表有子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();
}
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.
//如果没有子view消费事件,那么就调用view的dispatchTouchEvent方法,因为下面方法中child为null的
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;
//如果事件已经传递并且被当前子view消费的,那么就handled为true,那么当前方法就返回true
if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
handled = true;
} else {
final boolean cancelChild = resetCancelNextUpFlag(target.child)
|| intercepted;
//传递给当前target的child,看是否消费事件
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源码中,我们首先判断是否要调用拦截方法onInterceptTouchEvent询问是否拦截事件,可以看到在down事件或者有子view消费事件的时候,而且又允许拦截的情况下,会调用onInterceptTouchEvent方法,就是说mFirstTouchTarget ==null的时候,代表ViewGroup要处理事件序列,此时我们将不再需要调用拦截方法询问是否拦截了。
接下来就是循环遍历ViewGroup的所有child了,首先从是将事件分发给最后一个子view,即最后添加的那个子view,通过dispatchTransformedTouchEvent方法将事件分发,注意这个方法有个参数child,当child不等于null的时候,就会调用child的dispatchTouchEvent方法,返回值代表child是否消费了事件,然后我们通过newTouchTarget = addTouchTarget(child, idBitsToAssign)给newTouchTarget赋值,此时就代表有子view消费事件了,然后跳出循环。我们看看dispatchTransformedTouchEvent源码如下:
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;
}
在这个方法中很重要的是,判断child是否为null,很明显非null的时候,就会将事件分给child,否则交给父类view去处理事件。我们继续往下看,看代码:
if (mFirstTouchTarget == null) {
// No touch targets so treat this as an ordinary view.
handled = dispatchTransformedTouchEvent(ev, canceled, null,
TouchTarget.ALL_POINTER_IDS);
} else {
//省略代码..................
}
上面代码可以看到,当mFirstTouchTarget为null的时候,有两种情况,一种是ViewGroup没有子view消费事件,另外就是没有子view,即当前view不是ViewGroup,是一个View,此时dispatchTransformedTouchEvent方法child就是null,然后就会调用View类的dispatchTouchEvent,将事件交由其处理。其实到这里ViewGroup的事件分发机制已经大体清楚了,就是首先会根据条件是否调用拦截方法onInterceptTouchEvent询问是否拦截事件,然后就会遍历子view逐一去询问是否消费事件。
上面我们主要分析了ViewGroup的dispatchTouchEvent方法,看到ViewGroup是怎么进行事件的分发的,下面我们来看看View的dispatchTouchEvent方法是怎么处理事件的,view的这个方法在两种情况下会被调用,一种是事件分发到最后的view不是ViewGroup,另一种是ViewGroup中没有子view消费事件,也会调用。主要代码如下:
//view的处理事件的方法
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;
}
//首先看我们有没有设置mOnTouchListener 监听,如果有就将事件传递给它的onTouch方法
//noinspection SimplifiableIfStatement
ListenerInfo li = mListenerInfo;
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;
}
我们可以看到,如果view设置了onTouchListener监听,会将事件先交由它的onTouch方法处理,然后如果没有消费的话再交给onTouchEvent去处理,下面我们看看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 (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();
}
//执行点击事件
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;
//省略代码。。。。。。。。。。。。。。。。
}
return true;
}
return false;
}
我们这里主要看up事件,如果view是可以点击的话,我们在这里会执行performClick方法,可以看到如果view是可点击的或者可长按的,onTouchEvent就会返回true,否则返回false,false就代表此事件没有被消费。
通过上面的总结分析,我们主要掌握ViewGroup和View的dispatchTouchEvent方法是怎么对事件进行处理的,理解了它们的处理机制也就基本掌握了事件分发机制了。下面我们总结一下,我们在自定义view的过程中,经常会碰到的一些需求处理:
-
如果我们需要在ViewGroup中拦截事件并且不让事件向下分发,那么我们可以重写onInterceptTouchEvent方法,然后重写onTouchEvent方法,在onTouchEvent方法中处理事件
-
如果我们需要在ViewGroup中处理事件,但是不拦截事件,那么就重写dispatchTouchEvent方法,在此方法中处理事件
-
处理滑动冲突的时候,我们重写onInterceptTouchEvent方法,根据具体业务逻辑判断是否拦截事件,也可以重写dispatchTouchEvent方法,所有事件先传给子view,如果子view需要就消费,不需要就返回给父容器的onTouchEvent方法消费。