Android事件分发原理分析

MotionEvent.ACTION_DOWN传递
在Android中,触碰控件的时候回产生一个ACTION_DOWN事件并逐层向下传递,首先ACTION_DOWN回先从Activity的dispatchTouchEvent方法开始向下传递:

public boolean dispatchTouchEvent(MotionEvent ev) { if (ev.getAction() == MotionEvent.ACTION_DOWN) { onUserInteraction(); } if (getWindow().superDispatchTouchEvent(ev)) { return true; } return onTouchEvent(ev); }

该方法调用了Activity中的Window的superDispatchTouchEvent方法,也就是PhoneWindow中:
@Override public boolean superDispatchTouchEvent(MotionEvent event) { return mDecor.superDispatchTouchEvent(event); }

然后接着调用mDecor的superDispatchTouchEvent方法,而mDecor就是我们熟悉的DecorView类的对象,是一个ViewGroup类型的,这里先大概了解一下Activity布局层级结构:

Android事件分发原理分析
文章图片
image.png
从图上可以看出,Activity实际上是包含了一个PhoneWindow,然后在PhoneWindow中又包含了DecorView的ViewGroup,我们通过setContentView为Activity设置的布局文件最终是添加到DecorView下的,也就是我们的xml布局文件最终是DecorView的child,所以当ACTION_DOWN传递到DecorView的superDispatchTouchEvent方法的时候:
public boolean superDispatchTouchEvent(MotionEvent event) { return super.dispatchTouchEvent(event); }

实际上DecorView的superDispatchTouchEvent就是调用了ViewGroup的dispatchTouchEvent方法继续往子层级继续传递,ViewGroup的dispatchTouchEvent方法源码太长了,这里就不贴上来了,在分析到关键部分的时候只贴关键代码吧。在ViewGroup的dispatchTouchEvent方法里,首先:
// 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(); }

看注释是出来初始化的ACTION_DOWN事件,为什么要这么作?我的理解是ACTION_DOWN应该作为触摸动作最先发生的事件,一个触摸动作首先发生了ACTION_DOWN事件,然后如果又移动就会发生ACTION_MOVEDMOVE事件,接着再抬手发生了ACTION_UP事件,当然如果你没抬手,只是吧触碰点移动出了控件的范围,那应该是发生ACTION_CANCEL事件(这个有些手机可能不会发生ACTION_CANCEL事件而是发生ACTION_UP事件),这才是一个完整的触摸动作,所以对于一个单点触摸动作来说ACTION_DOWN在这个动作完成之前ACTION_DOWN只会发生一次,因此这里需要吧控件之前发生的一些触摸事件留下来的touch状态信息抛出ACTION_CANCEL事件来结束,然后清空该控件的touch信息与状态恢复到ACTION_DOWN事件发生之前的状态再接着传递ACTION_DOWN事件:
/** * Cancels and clears all touch targets. */ private void cancelAndClearTouchTargets(MotionEvent event) { if (mFirstTouchTarget != null) { boolean syntheticEvent = false; if (event == null) { final long now = SystemClock.uptimeMillis(); event = MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0.0f, 0.0f, 0); event.setSource(InputDevice.SOURCE_TOUCHSCREEN); syntheticEvent = true; }for (TouchTarget target = mFirstTouchTarget; target != null; target = target.next) { resetCancelNextUpFlag(target.child); dispatchTransformedTouchEvent(event, true, target.child, target.pointerIdBits); } clearTouchTargets(); if (syntheticEvent) { event.recycle(); } } }

dispatchTransformedTouchEvent(event, true, target.child, target.pointerIdBits)就是把当前的ACTION_DOWN先设置成ACTION_CANCEL派发给子控件然后再恢复ACTION_DOWN状态:
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; }

清空touch信息只会,继续恢复ACTION_DOWN的传递,在ViewGroup的dispatchTouchEvent方法中,ACTION_DOWN回执行到以下代码:
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; }

ACTION_DOWN事件回满足if分支,else暂时不管,在if分支中出现了一个disallowIntercept变量,这个是控制该控件是否允许拦截touch事件用的,由ViewGroup中requestDisallowInterceptTouchEvent方法来控制:
@Override public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {if (disallowIntercept == ((mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0)) { // We're already in this state, assume our ancestors are too return; }if (disallowIntercept) { mGroupFlags |= FLAG_DISALLOW_INTERCEPT; } else { mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT; }// Pass it up to our parent if (mParent != null) { mParent.requestDisallowInterceptTouchEvent(disallowIntercept); } }

如果disallowIntercept为true那就是不允许拦截,于是就不会继续调用onInterceptTouchEvent方法,如果为false,就是允许拦截,onInterceptTouchEvent方法将被调用:
public boolean onInterceptTouchEvent(MotionEvent ev) { if (ev.isFromSource(InputDevice.SOURCE_MOUSE) && ev.getAction() == MotionEvent.ACTION_DOWN && ev.isButtonPressed(MotionEvent.BUTTON_PRIMARY) && isOnScrollbarThumb(ev.getX(), ev.getY())) { return true; } return false; }

这个方法返回true表示触摸事件要被拦截,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 preorderedList = buildTouchDispatchChildList(); final boolean customOrder = preorderedList == null && isChildrenDrawingOrderEnabled(); 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); } 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; } } }

这里面的核心其实就是遍历该ViewGroup下的所有Child,如果当前的ViewGroup没有Child了,那么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); }

如果ViewGroup有Child,判断Child是否有资格接收触摸事件:
/** * Returns true if a child view can receive pointer events. * @hide */ private static boolean canViewReceivePointerEvents(@NonNull View child) { return (child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null; }/** * Returns true if a child view contains the specified point when transformed * into its coordinate space. * Child must not be null. * @hide */ protected boolean isTransformedTouchPointInView(float x, float y, View child, PointF outLocalPoint) { final float[] point = getTempPoint(); point[0] = x; point[1] = y; transformPointToViewLocal(point, child); final boolean isInView = child.pointInView(point[0], point[1]); if (isInView && outLocalPoint != null) { outLocalPoint.set(point[0], point[1]); } return isInView; }

子控件必须是可见并且触摸的坐标在控件范围内才能接收触摸事件,这里有一个小细节,我么可以学习如果来把触摸的坐标点是否在控件范围内这个判断:
public boolean pointInView(float localX, float localY, float slop) { return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && localY < ((mBottom - mTop) + slop); }

注意坐标点的转化。继续来分析触摸事件ACTION_DOWN的传递,在找到能够接收ACTION_DOWN的Child之后,会执行dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign),然后根据返回值决定是否把事件继续往下一个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; }

如果dispatchTransformedTouchEvent返回true表示事件已经被消费,那就会直接break,事件就不会继续传递给下一个Child了,返回false的就会继续循环把事件传递给下一个Child
// 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); }

child == null的时候说明ViewGroup没有child,直接会调用到View的dispatchTouchEvent,其实就是ViewGroup本身;
child != null的时候就会执行child.dispatchTouchEvent(transformedEvent),child是View类型的,再看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)) { 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; } }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是否是enabled的,如果是,就会触发这个View的OnTouchListener的onTouch,然后根据onTouch的返回值决定是否触发View的onTouchEvent,也就是说OnTouchListener会比onTouchEvent先执行,到这ACTION_DOWN事件传递结束,下面来总结以下传递流程与顺序:

Android事件分发原理分析
文章图片
image.png MotionEvent.ACTION_UP的传递
上面提到,一个单点完整的触摸动作是从ACTION_DOWN开始,并以ACTION_UP或者ACTION_CANCEL结束的,ACTION_UP是在ACTION_DOWN已经发生的情况下再去基于当前View的一些特性,例如是否可点击,事件是否被消费来决定ACTION_UP是否能不能到达一些控件的,ACTION_UP依然也是从Activity的dispatchTouchEvent方法开始往下逐层传递,这边可通过对比Button和TextView对于ACTION_UP的不同处理作比较:
  • Button与TextView对于ACTION_UP的区别,Buton是可点击的isClickable方法返回true,而TextView是不可点击的isClickable方法返回false,所以Button在处理ACTION_DOWN的时候,会在View的onTouchEvent返回true:
if (!result && onTouchEvent(event)) { result = true; }

因此直接导致了View的dispatchTouchEvent方法也返回true,由此逐级继续向上返回这个true,因此Button的父控件,Activity的dispatchTouchEvent方法都会纷纷的返回true,在ViewGroup当中收到View的dispatchTouchEvent返回true的时候会执行以下代码:
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; }

因为View的dispatchTouchEvent返回true,所以也返回true,原因是dispatchTransformedTouchEvent中去分发执行了View的dispatchTouchEvent:
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); }

handled就是View的dispatchTouchEvent返回的值,表示事件已经被消费了,dispatchTransformedTouchEvent返回true之后,就执行了newTouchTarget = addTouchTarget(child, idBitsToAssign):
private TouchTarget addTouchTarget(@NonNull View child, int pointerIdBits) { final TouchTarget target = TouchTarget.obtain(child, pointerIdBits); target.next = mFirstTouchTarget; mFirstTouchTarget = target; return target; }

把子控件赋值给了mFirstTouchTarget,如果mFirstTouchTarget不为null,当下一个事件ACTION_UP传递进入ViewGroup的时候:
// 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; } }

上面是ViewGroup的dispatchTouchEvent中对于mFirstTouchTarget是否为null的不同处理,对于Button来说,由于ACTION_DOWN被消费了,因此mFirstTouchTarget != null,所以会通过mFirstTouchTarget.child来把ACTION_UP继续分发给子View,前提当然是当前这个ViewGroup满足事件分发条件,例如事件未被拦截,这样ACTION_UP就能顺利的传递到子控件了,因此这就是为什么Button点击后能够收到ACTION_UP,而对于TextView而言,这里就不一样了,由于TextView是不可点击的,因此在执行View的onTouchEvent的时候会返回false,这将导致它的父控件ViewGroup的dispatchTransformedTouchEvent也返回false,所以dispatchTouchEvent返回false,因此mFirstTouchTarget并不会被初始化,即不会执行addTouchTarget方法,所以mFirstTouchTarget为null,当ACTION_UP从Activity传进ViewGroup的时候,发现mFirstTouchTarget == null,就是执行:
if (mFirstTouchTarget == null) { // No touch targets so treat this as an ordinary view. handled = dispatchTransformedTouchEvent(ev, canceled, null, TouchTarget.ALL_POINTER_IDS); }

可以看到dispatchTransformedTouchEvent的child参数(方法的第三个参数)直接传了一个null,这样将导致当前的ViewGroup无法将ACTION_UP传递给它的子控件,而是直接调用了:
if (child == null) { handled = super.dispatchTouchEvent(transformedEvent); }

由于ViewGroup的父类是View,因此最终执行了View的dispatchTouchEvent,所以ACTION_UP就只传递到了ViewGroup,并不再往下传递,对于Activity的层级结构来说我们通过setContentView设置的布局是嵌套在DecorView中的,DecorView是一个ViewGroup,ACTION_UP是从Activity的dispatchTouchEvent传递进来的,因此ACTION_UP最终只会传递到DecorView这层,而不会传递到我们设置的布局控件了,当把TextView通过setClickable(true)设置成可点击的时候,TextView和它的父控件ViewGroup就能收到ACTION_UP事件,当把Button通过setClickable(false),那么Button就喝TextView一样,无法收到ACTION_UP事件,下面来搞一个Demo,Demo地址:https://github.com/liuhongda/TouchEventDemo,Activity布局文件:

MainActivity:
public class MainActivity extends Activity {static final String tag = "MainActivity"; MyButton myButton; MyTextView myTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); myTextView = (MyTextView) findViewById(R.id.my_tv); myButton = (MyButton) findViewById(R.id.my_btn); myTextView.setClickable(true); myButton.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { Log.d(tag, "myButton onTouch:" + event); return false; } }); myTextView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { Log.d(tag, "myTextView onTouch:" + event); return false; } }); Log.d(tag, "tv:" + myTextView.isClickable()); Log.d(tag, "btn:" + myButton.isClickable()); }@Override public boolean onTouchEvent(MotionEvent event) { Log.d(tag, "onTouchEvent:" + event); return super.onTouchEvent(event); }@Override public boolean dispatchTouchEvent(MotionEvent ev) { Log.d(tag, "dispatchTouchEvent:" + ev); boolean touch = super.dispatchTouchEvent(ev); Log.d(tag, "dispatchTouchEvent:" + touch); return touch; } }

MyRelativeLayout:
public class MyRelativeLayout extends RelativeLayout {static final String tag = "MyRelativeLayout"; public MyRelativeLayout(Context context) { super(context); }public MyRelativeLayout(Context context, AttributeSet attrs) { super(context, attrs); }public MyRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); }@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) public MyRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); }@Override public boolean dispatchTouchEvent(MotionEvent ev) { Log.d(tag, "dispatchTouchEvent:" + ev); return super.dispatchTouchEvent(ev); }@Override public boolean onInterceptTouchEvent(MotionEvent ev) { Log.d(tag, "onInterceptTouchEvent:" + ev.toString()); boolean touch = super.onInterceptTouchEvent(ev); Log.d(tag, "onInterceptTouchEvent:" + touch); return touch; }@Override public boolean onTouchEvent(MotionEvent event) { Log.d(tag, "onTouchEvent:" + event); return super.onTouchEvent(event); }@Override public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { Log.d(tag, "requestDisallowInterceptTouchEvent"); super.requestDisallowInterceptTouchEvent(disallowIntercept); } }

MyTextView:
public class MyTextView extends android.support.v7.widget.AppCompatTextView {static final String tag = "MyTextView"; public MyTextView(Context context) { super(context); }public MyTextView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); }public MyTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); }@Override public boolean dispatchTouchEvent(MotionEvent event) { Log.d(tag, "dispatchTouchEvent:" + event); return super.dispatchTouchEvent(event); }@Override public boolean onTouchEvent(MotionEvent event) { Log.d(tag, "onTouchEvent:" + event); boolean touch = super.onTouchEvent(event); Log.d(tag, "touch:" + touch); return touch; }@Override public boolean isClickable() { return super.isClickable(); } }

MyButton:
public class MyButton extends android.support.v7.widget.AppCompatButton {static final String tag = "MyButton"; public MyButton(Context context) { super(context); }public MyButton(Context context, AttributeSet attrs) { super(context, attrs); }public MyButton(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); }@Override public boolean dispatchTouchEvent(MotionEvent event) { Log.d(tag, "dispatchTouchEvent:" + event); return super.dispatchTouchEvent(event); }@Override public boolean onTouchEvent(MotionEvent event) { Log.d(tag, "onTouchEvent:" + event); boolean touch = super.onTouchEvent(event); Log.d(tag, "touch:" + touch); return touch; }@Override public boolean isClickable() { return super.isClickable(); } }

点击TextView的ACTION_DOWN和ACTION_UP的传递结果打印:
12-06 00:10:27.258 13203-13203/? D/MainActivity: dispatchTouchEvent:MotionEvent { action=ACTION_DOWN, actionButton=0, id[0]=0, x[0]=185.09766, y[0]=105.0, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=51416868, downTime=51416868, deviceId=0, source=0x1002 } 12-06 00:10:27.258 13203-13203/? D/MyRelativeLayout: dispatchTouchEvent:MotionEvent { action=ACTION_DOWN, actionButton=0, id[0]=0, x[0]=185.09766, y[0]=21.0, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=51416868, downTime=51416868, deviceId=0, source=0x1002 } 12-06 00:10:27.258 13203-13203/? D/MyRelativeLayout: onInterceptTouchEvent:MotionEvent { action=ACTION_DOWN, actionButton=0, id[0]=0, x[0]=185.09766, y[0]=21.0, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=51416868, downTime=51416868, deviceId=0, source=0x1002 } 12-06 00:10:27.258 13203-13203/? D/MyRelativeLayout: onInterceptTouchEvent:false 12-06 00:10:27.258 13203-13203/? D/MyTextView: dispatchTouchEvent:MotionEvent { action=ACTION_DOWN, actionButton=0, id[0]=0, x[0]=185.09766, y[0]=21.0, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=51416868, downTime=51416868, deviceId=0, source=0x1002 } 12-06 00:10:27.258 13203-13203/? D/MainActivity: myTextView onTouch:MotionEvent { action=ACTION_DOWN, actionButton=0, id[0]=0, x[0]=185.09766, y[0]=21.0, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=51416868, downTime=51416868, deviceId=0, source=0x1002 } 12-06 00:10:27.259 13203-13203/? D/MyTextView: onTouchEvent:MotionEvent { action=ACTION_DOWN, actionButton=0, id[0]=0, x[0]=185.09766, y[0]=21.0, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=51416868, downTime=51416868, deviceId=0, source=0x1002 } 12-06 00:10:27.259 13203-13203/? D/MyTextView: touch:false 12-06 00:10:27.259 13203-13203/? D/MyRelativeLayout: onTouchEvent:MotionEvent { action=ACTION_DOWN, actionButton=0, id[0]=0, x[0]=185.09766, y[0]=21.0, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=51416868, downTime=51416868, deviceId=0, source=0x1002 } 12-06 00:10:27.259 13203-13203/? D/MainActivity: onTouchEvent:MotionEvent { action=ACTION_DOWN, actionButton=0, id[0]=0, x[0]=185.09766, y[0]=105.0, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=51416868, downTime=51416868, deviceId=0, source=0x1002 } 12-06 00:10:27.259 13203-13203/? D/MainActivity: dispatchTouchEvent:false 12-06 00:10:27.361 13203-13203/? D/MainActivity: dispatchTouchEvent:MotionEvent { action=ACTION_UP, actionButton=0, id[0]=0, x[0]=185.09766, y[0]=105.0, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=51416972, downTime=51416868, deviceId=0, source=0x1002 } 12-06 00:10:27.361 13203-13203/? D/MainActivity: onTouchEvent:MotionEvent { action=ACTION_UP, actionButton=0, id[0]=0, x[0]=185.09766, y[0]=105.0, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=51416972, downTime=51416868, deviceId=0, source=0x1002 } 12-06 00:10:27.361 13203-13203/? D/MainActivity: dispatchTouchEvent:false

日志打印中MyTextView: touch:false是MyTextView的onTouchEvent方法里面打印的:
@Override public boolean onTouchEvent(MotionEvent event) { Log.d(tag, "onTouchEvent:" + event); boolean touch = super.onTouchEvent(event); Log.d(tag, "touch:" + touch); return touch; }

而ACTION_UP确实只打印了MainActivity级别的,MainActivity以下的就没打印了,ACTION_UP是只传到了DecorView这一层,大家可以通过打断点的方式跟进DecorView的dispatchTouchEvent,而点击Button后ACTION_DOWN与ACTION_UP的传递:
12-06 00:16:39.884 13203-13203/com.lhd.touchevent D/MainActivity: dispatchTouchEvent:MotionEvent { action=ACTION_DOWN, actionButton=0, id[0]=0, x[0]=205.09277, y[0]=220.07812, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=51789495, downTime=51789495, deviceId=0, source=0x1002 } 12-06 00:16:39.884 13203-13203/com.lhd.touchevent D/MyRelativeLayout: dispatchTouchEvent:MotionEvent { action=ACTION_DOWN, actionButton=0, id[0]=0, x[0]=205.09277, y[0]=136.07812, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=51789495, downTime=51789495, deviceId=0, source=0x1002 } 12-06 00:16:39.884 13203-13203/com.lhd.touchevent D/MyRelativeLayout: onInterceptTouchEvent:MotionEvent { action=ACTION_DOWN, actionButton=0, id[0]=0, x[0]=205.09277, y[0]=136.07812, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=51789495, downTime=51789495, deviceId=0, source=0x1002 } 12-06 00:16:39.884 13203-13203/com.lhd.touchevent D/MyRelativeLayout: onInterceptTouchEvent:false 12-06 00:16:39.884 13203-13203/com.lhd.touchevent D/MyButton: dispatchTouchEvent:MotionEvent { action=ACTION_DOWN, actionButton=0, id[0]=0, x[0]=205.09277, y[0]=70.078125, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=51789495, downTime=51789495, deviceId=0, source=0x1002 } 12-06 00:16:39.885 13203-13203/com.lhd.touchevent D/MainActivity: myButton onTouch:MotionEvent { action=ACTION_DOWN, actionButton=0, id[0]=0, x[0]=205.09277, y[0]=70.078125, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=51789495, downTime=51789495, deviceId=0, source=0x1002 } 12-06 00:16:39.885 13203-13203/com.lhd.touchevent D/MyButton: onTouchEvent:MotionEvent { action=ACTION_DOWN, actionButton=0, id[0]=0, x[0]=205.09277, y[0]=70.078125, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=51789495, downTime=51789495, deviceId=0, source=0x1002 } 12-06 00:16:39.885 13203-13203/com.lhd.touchevent D/MyButton: touch:true 12-06 00:16:39.885 13203-13203/com.lhd.touchevent D/MainActivity: dispatchTouchEvent:true 12-06 00:16:40.004 13203-13203/com.lhd.touchevent D/MainActivity: dispatchTouchEvent:MotionEvent { action=ACTION_UP, actionButton=0, id[0]=0, x[0]=205.09277, y[0]=220.07812, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=51789615, downTime=51789495, deviceId=0, source=0x1002 } 12-06 00:16:40.004 13203-13203/com.lhd.touchevent D/MyRelativeLayout: dispatchTouchEvent:MotionEvent { action=ACTION_UP, actionButton=0, id[0]=0, x[0]=205.09277, y[0]=136.07812, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=51789615, downTime=51789495, deviceId=0, source=0x1002 } 12-06 00:16:40.004 13203-13203/com.lhd.touchevent D/MyRelativeLayout: onInterceptTouchEvent:MotionEvent { action=ACTION_UP, actionButton=0, id[0]=0, x[0]=205.09277, y[0]=136.07812, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=51789615, downTime=51789495, deviceId=0, source=0x1002 } 12-06 00:16:40.004 13203-13203/com.lhd.touchevent D/MyRelativeLayout: onInterceptTouchEvent:false 12-06 00:16:40.004 13203-13203/com.lhd.touchevent D/MyButton: dispatchTouchEvent:MotionEvent { action=ACTION_UP, actionButton=0, id[0]=0, x[0]=205.09277, y[0]=70.078125, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=51789615, downTime=51789495, deviceId=0, source=0x1002 } 12-06 00:16:40.005 13203-13203/com.lhd.touchevent D/MainActivity: myButton onTouch:MotionEvent { action=ACTION_UP, actionButton=0, id[0]=0, x[0]=205.09277, y[0]=70.078125, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=51789615, downTime=51789495, deviceId=0, source=0x1002 } 12-06 00:16:40.005 13203-13203/com.lhd.touchevent D/MyButton: onTouchEvent:MotionEvent { action=ACTION_UP, actionButton=0, id[0]=0, x[0]=205.09277, y[0]=70.078125, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=51789615, downTime=51789495, deviceId=0, source=0x1002 } 12-06 00:16:40.005 13203-13203/com.lhd.touchevent D/MyButton: touch:true 12-06 00:16:40.005 13203-13203/com.lhd.touchevent D/MainActivity: dispatchTouchEvent:true

【Android事件分发原理分析】MyButton: touch:true,这是MyButton的onTouchEvent里面的打印,而ACTION_UP确实有被MyButton以及MyRelativeLayout收到,日志证实了我们上面基于源码的分析是正确的
总结
  • 事件触摸机制的几个重要的方法:
  1. ViewGroup中的dispatchTouchEvent方法,负责把事件分发给子View,如果没有子View,就自己处理了
  2. ViewGroup的onInterceptTouchEvent方法,是否拦截触摸事件,控制触摸事件的流向,true表示拦截事件,false表示不拦截
  3. ViewGroup的requestDisallowInterceptTouchEvent方法控制onInterceptTouchEvent是否可以拦截,如果requestDisallowInterceptTouchEvent传进去的方法参数disallowIntercept为true表示不允许拦截,false表示允许拦截
  4. View的dispatchTouchEvent负责把触摸事件进行处理,这里已经是触摸事件传递的终点了,不会再往下传递了,里面回去触发OnTouchListener,onTouchEvent,注意OnTouchListener会比onTouchEvent先触发,如果OnTouchListener返回true,那么事件就会被消费掉,onTouchEvent将不会被触发,对于View来说还有OnClickListener和OnLongClickListener事件,这些都是在onTouchEvent中在ACTION_UP来的时候处理判断的,因此如果OnTouchListener这里把触摸事件拦截了,那OnClickListener和OnLongClickListener事件将无法触发到

    推荐阅读