在上一篇文章Android事件分发机制详解(一)中,介绍了View
的事件分发,这篇文章主要介绍ViewGroup
的事件分发机制以及点击和触摸事件是怎么传递的。
在上一篇文章中,我们分析过在点击或者触摸View
后,事件首先是传到View
的dispatchTouchEvent
方法中处理,在ViewGroup
也是同样的,首先也传到ViewGroup
中的dispatchTouchEvent
方法中处理,因为ViewGroup
是继承View
的。ViewGroup
的事件分发与View
的事件分发有点不同,ViewGroup
事件分发过程中多了一个方法onInterceptTouchEvent
,这个方法是用来拦截事件的,具体是怎么拦截的,我们来分析。
先来看看ViewGroup::dispatchTouchEvent
的源码,源码很长,只贴关键片段:
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
...
boolean handled = false;
...
// 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;
}
...
// Check for cancelation.
final boolean canceled = resetCancelNextUpFlag(this)
|| actionMasked == MotionEvent.ACTION_CANCEL;
if (!canceled && !intercepted) {
...
}
// 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);
}
...
return handled;
}
我们先来看ViewGroup
是怎么拦截事件的,从上面的源码中第一个条件语句,可以看出来,在actionMasked == MotionEvent.ACTION_DOWN || mFirstTouchTarget != null
时,才会出现intercpted = false
的情况,而mFirstTouchTarget
是在if (!canceled && !intercepted)
条件语句中赋值的,这里没有贴出来,说明一下,是在addTouchTarget
方法中赋值的,有兴趣的童鞋去读下源码就知道了。所以当intercpted
为true时,mFirstTouchTarget
总会为null
,所以这里可以得出一个结论,onInterceptTouchEvent
方法只有在MotionEvent.ACTION_DOWN
时才会触发。
回到主题,当onInterceptTouchEvent
方法返回true
时,intercepted = true
,那么mFirstTouchTarget == null
成立,然后就会执行dispatchTransformedTouchEvent
方法:
private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
View child, int desiredPointerIdBits) {
final boolean handled;
...
// Perform any necessary transformations and dispatch.
if (child == null) {
handled = super.dispatchTouchEvent(transformedEvent);
} else {
final float offsetX = mScrollX - child.mLeft;
final float offsetY = mScrollY - child.mTop;
transformedEvent.offsetLocation(offsetX, offsetY);
if (! child.hasIdentityMatrix()) {
transformedEvent.transform(child.getInverseMatrix());
}
handled = child.dispatchTouchEvent(transformedEvent);
}
// Done.
transformedEvent.recycle();
return handled;
}
当mFirstTouchTarget == null
成立,dispatchTransformedTouchEvent
的参数child
为null
,所以直接调用super.dispatchTouchEvent(transformedEvent)
,super
就是View
,这就回到了上篇文章中的流程了,不懂的可以回去看看上篇文章。既然执行的是super.dispatchTouchEvent(transformedEvent)
,那么事件就不会传递给子控件了,也就是说拦截掉了事件,ViewGroup
自己处理了。
我们再来看看当intercepted == false
时的情况,众所周知,当事件没有被拦截,肯定会传递给子控件的dispatchTouchEvent
处理,到底是怎么传递的,请看下面if (!canceled && !intercepted)
条件代码片段:
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);
}
这里是遍历子控件,当执行到if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign))
时,child
不为空,再看dispatchTransformedTouchEvent
方法,会执行child.dispatchTouchEvent
方法,如果child.dispatchTouchEvent
返回false
,还是不会执行addTouchTarget
方法,也就是说mFirstTouchTarget
还是为空,后续的事件,如ACTION_UP
,ACTION_MOVE
都默认被拦截了,不会再传给child
,这就是上一篇文章预留问题的答案,dispatchTouchEvent
的返回值的作用,这里也特别说明一下,ViewGroup
继承View
,所以ViewGroup::dispatchTouchEvent
的返回值也是一样的,因为ViewGroup
也可以为子控件。顺便提一下,onTouchEvent
的返回值与dispatchTouchEvent
的返回值作用是相同的,上一篇的代码仔细看过就会明白,就在View::dispatchTouchEvent
方法中调用onTouchEvent
的地方。
结合上一篇文章,得出简单流程图如下:
经过前面的分析,已经了解了View
以及ViewGroup
的事件分发机制,那么问题来了,当我们点击一个按钮时,事件是怎么传到按钮的?
下面我们来继续从源码分析分析,相信大家都知道一个Activity
对应一个Window
,我们点击按钮时最先触发的是顶层View
–DecorView
的dispatchTouchEvent
方法,至于点击屏幕后事件怎么传递给DecorView
的,这里涉及到WindowManagerService
和ViewRootImpl
创建窗口,有点复杂,暂时不分析。
先来看看DecorView::dispatchTouchEvent
方法:
public boolean dispatchTouchEvent(MotionEvent ev) {
final Window.Callback cb = mWindow.getCallback();
return cb != null && !mWindow.isDestroyed() && mFeatureId < 0
? cb.dispatchTouchEvent(ev) : super.dispatchTouchEvent(ev);
}
该方法中mWindow.getCallback
就是我们的Activity
,因为在为Activity
创建窗口时,会调用Activity
的attach
方法,在attach
方法中执行了mWindow.setCallback(this)
,所以这里返回的是Activity
。
也就是说在这里其实是调用Activity::dispatchTouchEvent
方法。
我们来看看Activity::dispatchTouchEvent
方法的实现(源码片段):
public boolean dispatchTouchEvent(MotionEvent ev) {
...
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
onUserInteraction();
}
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
}
onUserInteraction
是个空方法,不用去分析,看第二个条件if (getWindow().superDispatchTouchEvent(ev))
,getWindow
返回的是一个PhoneWindow
,这里的条件相当于调用PhoneWindow::superDispatchTouchEvent(ev)
,它的源码是:
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
return mDecor.superDispatchTouchEvent(event);
}
很简单的一段代码,直接调用mDecor
的superDispatchTouchEvent
方法。mDecor
是在PhoneWindow
构造方法里初始化的:
mDecor = (DecorView) preservedWindow.getDecorView();
也就是说mDecor
是一个DecorView
对象。再看DecorView::superDispatchTouchEvent
方法:
public boolean superDispatchTouchEvent(MotionEvent event) {
return super.dispatchTouchEvent(event);
}
DecorView
继承于FrameLayout
,而FrameLayout
继承于ViewGroup
,最终还是调用了ViewGroup
的dispatchTouchEvent
方法,后面的流程就和我们前面分析的ViewGroup
事件分发相同了,Over!