Android6.0 ViewGroup/View 事件分发机制详解
Posted HanyeeWang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android6.0 ViewGroup/View 事件分发机制详解相关的知识,希望对你有一定的参考价值。
之前自认为对于android的事件分发机制还算比较了解,直到前一阵偶然跟人探讨该问题,才发现自己以前的理解有误,惭愧之余遂决定研习源码,彻底弄明白Android的事件分发机制,好了废话少说,直接开干。
首先,我们对Android中的touch事件做一下总结,主要分为以下几类:
1、Action_Down 用户手指触碰到屏幕的那一刻,会触发该事件;
2、Action_Move 在触碰到屏幕之后,手指开始在屏幕上滑动,会触发Action_Move事件;
3、Action_Up 在用户手指从屏幕上离开那一刻开始,会触发Action_Up事件;
4、Action_Cancel Cancel事件一般跟Up事件的处理是一样的,是由系统代码自己去触发,比如子view的事件被父view给拦截了,之前被分发的子view就会被发送cancel事件,或者用户手指在滑动过程中移出了边界。另外,在有多点触控事件时,还会陆续触发ACTION_POINTER_DOWN、ACTION_POINTER_UP等事件。
其次,我们知道Android中负责事件分发机制的方法主要有以下三个:
1、dispatchTouchEvent(MotionEvent event) --- 分发事件
我们知道当用户触摸到手机屏幕时,最先接收到事件并进行相应处理的应该是最外层的Activity,所以我们来看看Activity中是如何对事件进行分发的。
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
onUserInteraction();
}
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
}
从以上代码中我们可以看到调用getWindow().superDispatchTouchEvent(),而这里的getWindow()返回的是Window抽象类,其实就是PhoneWindow类,继承于Window抽象类,然后调用PhoneWindow的superDispatchTouchEvent(),
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
return mDecor.superDispatchTouchEvent(event);
}
从superDispatchTouchEvent()方法中可以看到,它又调用了mDecor的superDispatchTouchEvent()方法,再看mDecor的superDispatchTouchEvent()方法,
public boolean superDispatchTouchEvent(MotionEvent event) {
return super.dispatchTouchEvent(event);
}
而mDecor是何许人也,其实就是PhoneWindow中的一个内部类DecorView的实例对象,是Activity的Window窗口中最根部的父容器,我们平时在Activity的onCreate()方法中,通过setContentView()给设置的布局容器,都属于mDecor的子View mContentView对象的子view,而DecorView又继承于FrameLayout,FrameLayout又继承于ViewGroup,由此可知,Activity是如何将事件分发到相应的View当中去的:
Activity.dispatchTouchEvent(MotionEvent event) -> PhoneWindow.superDispatchTouchEvent(MotionEvent event) -> DecorView.superDispatchTouchEvent(MotionEvent event) -> FrameLayout.dispatchTouchEvent(MotionEvent event) -> ViewGroup.dispatchTouchEvent(MotionEvent event) -> 再逐级分发到各个ViewGroup/View当中去
另外从以上分析过程可以看出,有一点需注意,就是我们在继承ViewGroup或其子类复写dispatchTouchEvent时,在方法最后的返回值处,最好别直接写成return true或者return false,而应写成super.dispatchTouchEvent,否则无法对事件继续进行逐级分发,因为在ViewGroup类的dispatchTouchEvent(MotionEvent event)方法中,会对该布局容器内的所有子View进行遍历,然后再进行事件分发,详细分发过程稍后会给出。
2、onInterceptTouchEvent(MotionEvent event) --- 拦截事件
onInterceptTouchEvent(MotionEvent event) 方法只存在于ViewGroup当中,是用来对布局容器内子View的事件进行拦截的,如果父容器View对事件进行了拦截,即return true,则子View不会收到任何事件分发。
3、onTouchEvent(MotionEvent event) --- 处理消费事件
onTouchEvent(MotionEvent event)方法如果返回true,则表示该事件被当前View给消费掉了,它的父View的onTouchEvent()后续都不会得到调用,而是通过dispatchTouchEvent()逐级向上返回true到Activity;如果没人消费该事件,都返回false,则最终会交给Activity去进行处理。
在大致了解了dispatchTouchEvent、onInterceptTouchEvent、onTouchEvent的作用之后,现在我们最需要理清的就是这三者之间的调用关系如何,为此我自己写了一个测试Demo,界面如下:
屏幕中有ViewGroupA、ViewGroupB、ViewC,依次进行嵌套
测试代码如下:
<com.android.hanyee.widgets.ViewGroupA xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/viewGroupA"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@android:color/white">
<com.android.hanyee.widgets.ViewGroupB
android:id="@+id/viewGroupB"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="60dp"
android:orientation="vertical"
android:background="@android:color/holo_blue_dark">
<com.android.hanyee.widgets.ViewC
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="60dp"
android:background="@android:color/holo_green_dark" />
</com.android.hanyee.widgets.ViewGroupB>
</com.android.hanyee.widgets.ViewGroupA>
public class ViewGroupA extends LinearLayout {
public ViewGroupA(Context context) {
super(context);
}
public ViewGroupA(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ViewGroupA(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
Log.d("hanyee", this.getClass().getSimpleName() + " onInterceptTouchEvent -> " + ViewUtils.actionToString(ev.getAction()));
boolean result = super.onInterceptTouchEvent(ev);
Log.d("hanyee", this.getClass().getSimpleName() + " onInterceptTouchEvent return super.onInterceptTouchEvent(ev)=" + result);
return result;
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
Log.d("hanyee", this.getClass().getSimpleName() + " dispatchTouchEvent -> " + ViewUtils.actionToString(ev.getAction()));
boolean result = super.dispatchTouchEvent(ev);
Log.d("hanyee", this.getClass().getSimpleName() + " dispatchTouchEvent return super.dispatchTouchEvent(ev)= " + result);
return result;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
Log.d("hanyee", this.getClass().getSimpleName() + " onTouchEvent -> " + ViewUtils.actionToString(ev.getAction()));
boolean result = super.onTouchEvent(ev);
Log.d("hanyee", this.getClass().getSimpleName() + " onTouchEvent return super.onTouchEvent(ev)=" + result);
return result;
}
}
public class ViewGroupB extends LinearLayout {
public ViewGroupB(Context context) {
super(context);
}
public ViewGroupB(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ViewGroupB(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
Log.d("hanyee", this.getClass().getSimpleName() + " onInterceptTouchEvent -> " + ViewUtils.actionToString(ev.getAction()));
boolean result = super.onInterceptTouchEvent(ev);
Log.d("hanyee", this.getClass().getSimpleName() + " onInterceptTouchEvent return super.onInterceptTouchEvent(ev)=" + result);
return result;
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
Log.d("hanyee", this.getClass().getSimpleName() + " dispatchTouchEvent -> " + ViewUtils.actionToString(ev.getAction()));
boolean result = super.dispatchTouchEvent(ev);
Log.d("hanyee", this.getClass().getSimpleName() + " dispatchTouchEvent return super.dispatchTouchEvent(ev)= " + result);
return result;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
Log.d("hanyee", this.getClass().getSimpleName() + " onTouchEvent -> " + ViewUtils.actionToString(ev.getAction()));
boolean result = super.onTouchEvent(ev);
Log.d("hanyee", this.getClass().getSimpleName() + " onTouchEvent return super.onTouchEvent(ev)=" + result);
return result;
}
}
public class ViewC extends View {
public ViewC(Context context) {
super(context);
}
public ViewC(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ViewC(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
Log.d("hanyee", this.getClass().getSimpleName() + " dispatchTouchEvent -> " + ViewUtils.actionToString(ev.getAction()));
boolean result = super.dispatchTouchEvent(ev);
Log.d("hanyee", this.getClass().getSimpleName() + " dispatchTouchEvent return super.dispatchTouchEvent(ev)= " + result);
return result;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
Log.d("hanyee", this.getClass().getSimpleName() + " onTouchEvent -> " + ViewUtils.actionToString(ev.getAction()));
boolean result = super.onTouchEvent(ev);
Log.d("hanyee", this.getClass().getSimpleName() + " onTouchEvent return super.onTouchEvent(ev)=" + result);
return result;
}
}
测试情景1:ViewGroupA、ViewGroupB、ViewC都没有消费事件
测试结果如下图:
由图中log可以看出,如果没有任何view消费事件的话,事件的传递顺序如下:
ViewGroupA.dispatchTouchEvent -> ViewGroupA.onInterceptTouchEvent(return false, 没有进行拦截) -> ViewGroupB.dispatchTouchEvent -> ViewGroupB.onInterceptTouchEvent(return false, 没有进行拦截) -> ViewC.dispatchTouchEvent -> ViewC.onTouchEvent(return false, 没有消费) -> ViewC.dispatchTouchEvent(return false, 将onTouchEvent的处理结果回传给ViewGroupB) -> ViewGroupB.onTouchEvent(return false, 也没有消费) -> ViewB.dispatchTouchEvent(return false, 将onTouchEvent的处理结果回传给ViewGroupA) -> ViewGroupA.onTouchEvent(return false, 也没有消费) -> ViewA.dispatchTouchEvent(return false, 最终将onTouchEvent的处理结果回传给Activity) -> Activity对事件进行最终处理
看到这里大伙可能会有些疑问,怎么就只有Down事件,而没有后续的Move、Up等事件,这是因为没有任何子View消费Down事件,Down事件最终被最外层的Activity给处理掉了,所以后续的所有Move、Up等事件都不会再分发给子View了,这里在后面的源码分析时会提到。
测试情景2:ViewC消费了事件
测试结果如下图:
由图中的log可以看出,一旦ViewC消费了Down事件,它的父容器ViewGroupB,祖父容器ViewGroupA的onTouchEvent都不会被调用了,而是直接通过dispatchTouchEvent将Down以及后续的Move、Up事件的处理结果返回至Activity。
测试情景3:仅点击ViewGroupB,让ViewGroupB消费事件
测试结果如下图:
从图中log可以看出,如果点击ViewGroupB,事件根本就不会传递到ViewC,ViewGroupB在消费了Down事件之后,再直接由父容器ViewGroupA的dispatchTouchEvent将ViewGroupB的onTouchEvent处理结果true回传给Activity,接下来后续的Move、Up事件都只会传递至ViewGroupB,而不会分发给ViewC。
测试情景4:让ViewGroupB对事件进行拦截
测试结果如图:
从图中log可以看出,如果ViewGroupB的onInterceptTouchEvent 返回true,对子view的事件进行拦截,则ViewC不会收到任何的点击事件,事件流变成了ViewGroupA -->ViewGroupB --> ViewGroupA,而没有经过ViewC
通过上述几种情景,我们可以大致了解,ViewGroupA的dispatchTouchEvent最先被调用,主要负责事件分发,然后会调用其onInterceptTouchEvent,如果返回true,则后续的ViewGroupB、ViewC都不会收到任何的点击事件,相反如果返回false,就放弃拦截事件,接着会遍历调用子View的dispatchTouchEvent方法将事件分发给ViewGroupB,如果ViewGroupB也没有拦截事件,则又会遍历调用子View的dispatchTouchEvent方法将事件分发给ViewC,如果ViewC在onTouchEvent中消费了事件返回true,则会将true通过dispatchTouchEvent方法逐级返回给其父容器直至Activity中,而且不会调用各个父容器对应的onTouchEvent方法,如果子View在onTouchEvent中没消费事件返回false,则通过dispatchTouchEvent方法将false返回给ViewGroupB,ViewGroupB就知道子View没有消费事件,就会调用自己的onTouchEvent来处理该事件,然后同理递归着ViewC在onTouchEvent中对于事件的处理逻辑,直到ViewGroupA将事件处理完反馈给Activity。
前面列了这么多现象,并归纳总结出以上dispatchTouchEvent、onInterceptTouchEvent、onTouchEvent之间的调用关系,相信大家对于Android事件的分发机制已经有了较为清晰的认识,但作为一名程序员,知其然,还得知其所以然,下面就带领大家一起研读下源码,看看到底为啥是这样的调用关系。从上面的情景log中大家应该可以看出,事件分发机制的最初始的入口就是ViewGroup的dispatchTouchEvent,下面就看看其代码:
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
}
// If the event targets the accessibility focused view and this is it, start
// normal event dispatch. Maybe a descendant is what will handle the click.
if (ev.isTargetAccessibilityFocus() && isAccessibilityFocusedViewOrHost()) {
ev.setTargetAccessibilityFocus(false);
}
boolean handled = false;
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.
cancelAndClearTouchTargets(ev);
resetTouchState();
}
// 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;
}
// 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;
if (!canceled && !intercepted) {
// If the event is targeting accessiiblity 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);
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 = buildOrderedChildList();
final boolean customOrder = preorderedList == null
&& isChildrenDrawingOrderEnabled();
final View[] children = mChildren;
for (int i = childrenCount - 1; i >= 0; i--) {
final int childIndex = customOrder
? getChildDrawingOrder(childrenCount, i) : i;
final View child = (preorderedList == null)
? children[childIndex] : preorderedList.get(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 (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.
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.
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;
}
这方法看似比较长,但我们只挑比较重要的点来看,在第32行会根据disallowIntercept来判断是否对子view来进行事件拦截,子view可以通过调用requestDisallowInterceptTouchEvent()方法来改变其值,如果可以进行拦截,则会调用onInterceptTouchEvent()方法,根据其返回值来判断需不需要对子View进行拦截,默认情况下onInterceptTouchEvent()方法返回的是false,所以如果我们在自定义View时如果想拦截的话,可以重写这个方法返回true就行了。
然后在第58行的if条件中,会根据是否取消canceled以及之前的是否拦截的标志intercepted来判断是否走进下面的逻辑代码块,这里我们只看intercepted,如果没有拦截,则会进入if后面的逻辑代码块,直到第89行的for循环,我们会看到ViewGroup在对所有子View进行遍历,以方便接下来的事件分发,再看到107、108行的判断,canViewReceivePointerEvents()用来判断是否该View能够接受处理事件,
private static boolean canViewReceivePointerEvents(View child) {
return (child.mViewFlags & VISIBILITY_MASK) == VISIBLE
|| child.getAnimation() != null;
}
可以看到只有当view处于可见状态且没有做动画时才能接收处理事件,再看isTransformedTouchPointInView()是用来判断当前事件是否触发在该view的范围之内,这里我们可以回想前面的测试情景3,当我们点击ViewGroupB时,ViewC完全没有收到任何事件,就是因为点击事件不在ViewC的范围之类,在isTransformedTouchPointInView()进行判断时就给过滤掉了,所以ViewC不会收到任何分发的事件。再看看第122行,会调用dispatchTransformedTouchEvent()来将事件分发给对应的view进行处理,让我们进入其方法体看看,
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;
}
// Calculate the number of pointers to deliver.
final int oldPointerIdBits = event.getPointerIdBits();
final int newPointerIdBits = oldPointerIdBits & desiredPointerIdBits;
// If for some reason we ended up in an inconsistent state where it looks like we
// might produce a motion event with no pointers in it, then drop the event.
if (newPointerIdBits == 0) {
return false;
}
// If the number of pointers is the same and we don't need to perform any fancy
// irreversible transformations, then we can reuse the motion event for this
// dispatch as long as we are careful to revert any changes we make.
// Otherwise we need to make a copy.
final MotionEvent transformedEvent;
if (newPointerIdBits == oldPointerIdBits) {
if (child == null || child.hasIdentityMatrix()) {
if (child == null) {
handled = super.dispatchTouchEvent(event);
} else {
final float offsetX = mScrollX - child.mLeft;
final float offsetY = mScrollY - child.mTop;
event.offsetLocation(offsetX, offsetY);
handled = child.dispatchTouchEvent(event);
event.offsetLocation(-offsetX, -offsetY);
}
return handled;
}
transformedEvent = MotionEvent.obtain(event);
} else {
transformedEvent = event.split(newPointerIdBits);
}
// 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;
}
我们看到在方法的末尾第55行,如果child为Null,则会调用ViewGroup的父类View的dispatchTouchEvent,否则就会调用child自身的dispatchTouchEvent方法进行事件分发处理。如果child是ViewGroup,则会又递归调用ViewGroup的dispatchTouchEvent方法逻辑进行事件分发,如果是View,则跟child为Null情况一样,都是会调到View的dispatchTouchEvent方法,接下来我们看看View的dispatchTouchEvent方法,
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)) {
//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;
}
}
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;
}
同样我们捡重点的看,第23行用来做过滤,看是否有窗口覆盖在上面,第27~29行三个判断条件说明了,当View的touch事件监听器不为空,View是enable状态,且touch事件监听回调方法onTouch方法返回true三个条件同时满足时,则会最终返回true,而且第33行的onTouchEvent方法都不会得到执行,这说明View的OnTouchListener监听回调的优先级要高于onTouchEvent,如果我们给View设置了OnTouchListener监听,并且在回调方法onTouch()中返回true,View的onTouchEvent就得不到执行,其dispatchTouchEvent方法就会直接返回true给父容器,相反如果返回false,或者没有设置OnTouchListener监听,才会执行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();
if ((viewFlags & ENABLED_MASK) == DISABLED) {
if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
setPressed(false);
}
// A disabled view that is clickable still consumes the touch
// events, it just doesn't respond to them.
return (((viewFlags & CLICKABLE) == CLICKABLE
|| (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
|| (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE);
}
if (mTouchDelegate != null) {
if (mTouchDelegate.onTouchEvent(event)) {
return true;
}
}
if (((viewFlags & CLICKABLE) == CLICKABLE ||
(viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) ||
(viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) {
switch (action) {
case MotionEvent.ACTION_UP:
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;
case MotionEvent.ACTION_DOWN:
mHasPerformedLongPress = false;
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);
checkForLongClick(0);
}
break;
case MotionEvent.ACTION_CANCEL:
setPressed(false);
removeTapCallback();
removeLongPressCallback();
mInContextButtonPress = false;
mHasPerformedLongPress = false;
mIgnoreNextUpEvent = false;
break;
case MotionEvent.ACTION_MOVE:
drawableHotspotChanged(x, y);
// Be lenient about moving outside of buttons
if (!pointInView(x, y, mTouchSlop)) {
// Outside button
removeTapCallback();
if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
// Remove any future long press/tap checks
removeLongPressCallback();
setPressed(false);
}
}
break;
}
return true;
}
return false;
}
从第7~16行可以看出,当View为disable状态,而又clickable时,是会消费掉事件的,只不过在界面上没有任何的响应。第18~22行,关于TouchDelegate,根据对官方文档的理解就是说有两个View, ViewB在ViewA中,ViewA比较大,如果我们想点击ViewA的时候,让ViewB去响应点击事件,这时候就需要使用到TouchDelegate, 简单的理解就是如果该View有自己的事件委托处理人,就交给委托人处理。从第24~26行可以看出,只有当View是可点击状态时,才会进入对应各种事件的详细处理逻辑,否则会直接返回false,表明该事件没有被消费。在第59行,可以看到在Action_Up事件被触发时,会执行performClick(),也就是View的点击事件,由此可知,view的onClick()回调是在Action_Up事件中被触发的。第134行直接返回了true,可以看出只要View处于可点击状态,并且进入了switch的判断逻辑,就会被返回true,表明该事件被消费掉了,也就是说只要View是可点击的,事件传到了其OnTouchEvent,都会被消费掉。而平时我们在调用setOnClickListener方法给View设置点击事件监听时,都会将其点击状态修改为可点击状态。
public void setOnClickListener(@Nullable OnClickListener l) {
if (!isClickable()) {
setClickable(true);
}
getListenerInfo().mOnClickListener = l;
}
追溯完View的事件分发流程,我们再返回到ViewGroup的dispatchTouchEvent方法的122行,如果对应得child消费了点击事件,就会通过对应的dispatchTouchEvent方法返回true并最终在122行使得条件成立,然后会进入到138行,调用addTouchTarget对newTouchTarget进行赋值,并且mFirstTouchTarget跟newTouchTarget的值都一样,然后将alreadyDispatchedToNewTouchTarget置为true
private TouchTarget addTouchTarget(View child, int pointerIdBits) {
TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
target.next = mFirstTouchTarget;
mFirstTouchTarget = target;
return target;
}
然后来到了163行,由于mFirstTouchTarget和newTouchTarget在addTouchTarget中都被赋值了,所以会直接进入172行的while循环,由于之前在138、139行对mFirstTouchTarget、newTouchTarget、alreadyDispatchedToNewTouchTarget都赋值了,使得174行条件成立,所以就直接返回true了,至此,ViewGroup就完成了对子View的遍历及事件分发,由于事件被消费掉了,所以ViewGroup对应的所有外围容器都会递归回调dispatchTouchEvent将true传递给Activity,到这也就解释了测试情景2的产生原理。在Down相关事件被消费掉之后,后续的Move、Up事件在dispatchTouchEvent方法的68~70行不符合判断条件,直接会来到179行的dispatchTransformedTouchEvent方法继续进行分发,待子View进行消费。
如果在ViewGroup的dispatchTouchEvent方法第58行被拦截了(对应测试情景4),或者107~108行不成立(对应测试情景3),或者122行返回false(即子View没有消费事件,对应测试情景1),则会直接进入到第163行,这时mFirstTouchTarget肯定为空,所以会又调用dispatchTransformedTouchEvent方法,而且传进去的child为空,最终就会直接走到dispatchTransformedTouchEvent方法的55行,然后调用super.dispatchTouchEvent,之后的处理逻辑跟前面调View的dispatchTouchEvent逻辑一样。
终上所述,整个Android的事件分发机制可以大致概括成如下的流程图
PS:以上相关的系统代码均为Android6.0的系统源码,整个Android事件分发机制还算有点复杂,完全给整明白写下这篇文章还费了些时间,中间查阅了一些资料,可能有些地方还存在些理解偏差,还请大家指出相互学习进步
以上是关于Android6.0 ViewGroup/View 事件分发机制详解的主要内容,如果未能解决你的问题,请参考以下文章
Android 事件分发MotionEvent.ACTION_DOWN 按下事件分发流程( Activity | ViewGroup | View )
Android 事件分发MotionEvent.ACTION_DOWN 按下事件分发流程( Activity | ViewGroup | View )