在开发中,我们经常要完成一些稍复杂的功能和交互。而这些交互往往不是触发型的,仅仅用各种动画是无法完成的,这时候就需要掌握View的一个核心知识:事件分发机制。这个比较重要也比较难,但实际上我们基本上每天都在直接或间接的跟它打交道。
public boolean dispatchTouchEvent(MotionEvent ev) {
boolean consume = false;
if (onInterceptTouchEvent(ev)) {
consume = onTouchEvent(ev);
} else {
consume = child.dispatchTouchEvent(ev);
}
return consume;
}
也就是说,一个ViewGroup调用自身的dispatchTouchEvent方法分发事件,如果自己要拦截,就交由自己的onTouchEvent方法处理事件,否则就让子View调用他们的dispatchTouchEvent继续分发,直到最终消费了事件。这种关系有点像递归。实际上,当事件传递到最终的子View上,还要看onTouchEvent的返回值,如果返回false则并不消费事件,继续又返回给上一级View消费。这种关系按照Activity -> Window -> View的顺序传递,可以用下图描述:
// Check for interception.
final boolean intercepted;
if (actionMasked == MotionEvent.ACTION_DOWN
|| mFirstTouchTarget != null) {
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
if (!disallowIntercept) {
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;
}
这段代码描述了是否拦截当前事件。mFirstTouchTouchTarget在ViewGroup的子元素成功处理事件时会被赋值并指向子元素,也就是说一旦ViewGroup拦截当前事件那么mFirstTouchTarget就为null。这样当ACTION_MOVE和ACTION_UP事件到来时,不满足判断条件中的任何一个,也就不会再调用onInterceptTouchEvent方法。就是说一旦开始拦截了事件,后续的拦截方法就不会再调用。
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 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);
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);
}
倒序遍历所有子元素,这也验证了前面的说法。先判断如果子元素接受不到事件或者事件坐标超出区域,则跳过本次循环。如果满足,则调用dispatchTransformedTouchEvent方法。跟踪这个方法发现多次调用,也就是决定其返回值的是以下代码:
if (child == null) {
handled = super.dispatchTouchEvent(transformedEvent);
} else {
handled = child.dispatchTouchEvent(transformedEvent);
}
可以看到最终调用的都是View的dispatchTouchEvent方法,如果返回true那么就跳出for循环,结束本次事件分发,并且会调用addTouchTarget方法为mFirstTouchTarget赋值。如果ViewGroup没有子元素,或者子元素处理事件时返回false,那么mFirstTouchTarget为null:
// Dispatch to touch targets.
if (mFirstTouchTarget == null) {
// No touch targets so treat this as an ordinary view.
handled = dispatchTransformedTouchEvent(ev, canceled, null,
TouchTarget.ALL_POINTER_IDS);
}
因为第三个参数(child)为null,会调用super.dispatchTouchEvent,也就是说,最终将事件交给了View处理。
public boolean dispatchTouchEvent(MotionEvent event) {
boolean result = false;
...
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;
if (li != null && li.mOnTouchListener != null
&& (mViewFlags & ENABLED_MASK) == ENABLED
&& li.mOnTouchListener.onTouch(this, event)) {
result = true;
}
if (!result && onTouchEvent(event)) {
result = true;
}
}
...
// 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在分发事件时,事件类型为ACTION_DOWN或者在本次事件结束时,则停止嵌套滚动(如果有的话)。比较关键的一点是会先判断有没有设置OnTouchListener,如果其中的onTouch回调方法返回true(一般是外部调用),那么result=true,逻辑判断onTouchEvent不会调用。也就是说,OnTouchListener的优先级高于onTouchEvent。现在看onTouchEvent方法:
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 ((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;
}
每次回调该方法时,都会先获取事件的相对坐标、View的状态、事件类型、View是否可点击。并且,即使View的enable属性为false,仍然不影响点击事件的消耗,而且clickable和longClickable只要有一个属性为true则onTouchEvent返回true,但是会将View的内部pressed状态置为false。比如一个Button正常按下时颜色变深,此处会没有效果。再看看对点击事件的具体处理:
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();
}
}
}
这一段代码是在ACTION_UP事件中的,当判断没有长按点击的任务时,移除长按事件的回调。并且判断当前没有正在进行的点击事件任务,则执行performClick方法:
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;
}
sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
notifyEnterOrExitForAutoFillIfNeeded(true);
return result;
}
可以看出,如果View设置了OnClickListener,那么最终会调用其onClick方法,也就是平时我最熟悉的点击事件。因此如果我们在页面初始化的时候需要不经动作触发,而执行一次点击事件,通常都会调用performClick方法,实现一次我们在onClick回调里面定义的行为。