对于Android事件分发机制,听别人说的在多,还不如自己看一遍事件传递的源码来的快,这样对事件的分发就会有一个清晰的理解,当遇到问题时,直接去源码中找答案就可以了,就不用去网上找答案。
对于事件分发,我这里是沿着一条主线切入的。对于Android开发来讲,ViewRootImpl这个类虽说我们平时接触的不多,但这个类却和Android中的很多功能都有关,对于Android的事件分发,在屏幕接收到触摸事件后,在运用层来说,事件最先分发到的就是这个类,对于view的测量、布局以及绘制也都是从这里开始的。
这里是基于Android API 26,ViewRootImpl对事件的分发最后传递给view是通过下面这一步:
boolean handled = mView.dispatchPointerEvent(event);
这里的这个mView就是在Activity的onCreate的setContentView()中生成的view,这个mView是一个DevorView,对于setContentView()是如何解析View不理解的可以参考Activity中setContentView()是如何解析view。dispatchPointerEvent()方法执行的就是View中的方法:
public final boolean dispatchPointerEvent(MotionEvent event) { if (event.isTouchEvent()) { return dispatchTouchEvent(event); } else { return dispatchGenericMotionEvent(event); } }
看到没有,这里就将事件分发给了dispatchTouchEvent(),可以说这里就是事件传递给我们处理的入口。接下来就去看看DecorView的dispatchTouchEvent():
@Override 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()返回的这个callback是在Activity中实现的,下面就是判断是传递给给Activity还是直接传递给父类(VIewGroup),这里走的是cb.dispatchTouchEvent(),这样就将事件传递给了Activity:
public boolean dispatchTouchEvent(MotionEvent ev) { if (ev.getAction() == MotionEvent.ACTION_DOWN) { onUserInteraction(); } if (getWindow().superDispatchTouchEvent(ev)) { return true; } return onTouchEvent(ev); }
这里可以看到当事件传给Activity的时候,如果只是想对按下的那一下处理,那就可以在我们的Activity中重写onUserInteraction()这个方法,接下来一个判断就是说你是否处理了事件,如果没有,那就交给Activity中的onTouchEvent()处理,上面的getWindow()实际返回的是PhoneWindow对象,这样就又将事件交给到了Window去处理了,那就去看下PhoneWindow是如何处理的:
@Override public boolean superDispatchTouchEvent(MotionEvent event) { return mDecor.superDispatchTouchEvent(event); }
就是简单的将事件又传回到了DecorView中,跟着代码往下走:
public boolean superDispatchTouchEvent(MotionEvent event) { return super.dispatchTouchEvent(event); }
将事件交给父类去处理,DecorView是父类是FragmentLayout,这里实际调用到的是ViewGroup中的方法,对于事件分发的主要逻辑就是在这里实现的:
@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); //复位所有的触摸状态,包括mFirstTouchTarget置null,mGroupFlags中FLAG_DISALLOW_INTERCEPT位 // 置为0(这里用到的就是位运算,不懂的自己可以好好体会下),FLAG_DISALLOW_INTERCEPT这个位主 // 要用于子类请求父类要不要对事件进行拦截,也就是执不执行父类的onInterceptTouchEvent(ev), // 这个置位是通过requestDisallowInterceptTouchEvent(boolean disallowIntercept)这个方法来实现的, // 传true意味着父类不会执行onInterceptTouchEvent(ev),传false就会执行,默认也是会执行的。 resetTouchState(); } // Check for interception. final boolean intercepted; //mFirstTouchTarget在按下之后是不为null的 if (actionMasked == MotionEvent.ACTION_DOWN || mFirstTouchTarget != null) { //这里默认是为false,如果设置了requestDisallowInterceptTouchEvent(boolean disallowIntercept)为true,那这里就为true 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 { 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) { //根据触摸的位置来寻找消费事件的view 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,找出那个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; } // getTouchTarget()判断消费事件的view是否包含在 mFirstTouchTarget 中 // 如果有返回target,如果没有返回 null,当找到了目标就跳出这个循环 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()这个方法会调用到子view的dispatchTouchEvent(), // 这里体现的就是递归调用了,不管怎样,最后还是会执行到View这 // 个类中的dispatchTouchEvent()方法 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(); //如果子view处理了这个事件,那就会进入到这里,就是将child包装到TouchTarget中,同时, // 这个方法还会对mFirstTouchTarget进行赋值 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. //进入到这里就说明没有找到消费这个事件的子view newTouchTarget = mFirstTouchTarget; while (newTouchTarget.next != null) { newTouchTarget = newTouchTarget.next; } newTouchTarget.pointerIdBits |= idBitsToAssign; } } } // Dispatch to touch targets. if (mFirstTouchTarget == null) { // 没有找到消费这个事件的子view,那就交由自己处理,如果自己还没有处理,那就在往上返回 handled = dispatchTransformedTouchEvent(ev, canceled, null, TouchTarget.ALL_POINTER_IDS); } else { // 分发TouchTarget,如果我们已经分发过,则避免分配给新的目标,如有必要,取消分发。 //这里其实就是Action.DOWN之后事件的处理,依然是递归调用 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; //将view事件进行分发,一般是在按下之后的后续事件会执行到这里 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; }在这个方法中主要是找到事件落到哪个view中,然后将事件传递给子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); //分发给自己还是子view,就是下面这个判断,后面的的逻辑也是基于这个,只是基于不同的情况做判断 //child为null就说明事件交由自己处理 //child不为null,就将事件分发下去 if (child == null) { handled = super.dispatchTouchEvent(event);//这个super就是View这个类的方法 } else { //child分为两种情况,一种是ViewGroup,一种不是,如果是,那就继续执行 // ViewGroup的diapatchTouchEvent()方法,上面已经分析了 //如果不是,那就执行View这个类的dispatchTouchEvent()方法 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; }到这,ViewGroup的事件传递就差不多了,接下来就该去看看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; } //这里主要是看有没有通过setOnTouchListener()将OnTouchListener这个回调设置到mListenerInfo中去, ListenerInfo li = mListenerInfo; if (li != null && li.mOnTouchListener != null //这里判断view是否可以点击,可通过android:clickable="true"进行设置 && (mViewFlags & ENABLED_MASK) == ENABLED && li.mOnTouchListener.onTouch(this, event)) { result = true; } //如果上面OnTouchListener这个回调中返回的true,那么下面这个onTouchEvent()将不会执行 //从这里也可以看出,onTouch()方法先于onTouchEvent()方法先执行,下面我们还会在onTouchEvent() // 这个方法中会调用到onClick()这个方法,这也就说明onTouchEvent方法先于onClick()方法 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; }
这个方法就是对事件进行分类,并按优先级进行了划分,优先级从高到低:ouTouch()-->onTOuchEvent()-->onClick(),具体怎么取执行,那就看我们有什么样的需求了。最后我们还是再来看看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 ((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; } if (mTouchDelegate != null) { if (mTouchDelegate.onTouchEvent(event)) { return true; } } 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) { //这是一个实现了Runnable接口的对象,设置的点击事件就是在run方法中执行的 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: if (event.getSource() == InputDevice.SOURCE_TOUCHSCREEN) { mPrivateFlags3 |= PFLAG3_FINGER_DOWN; } mHasPerformedLongPress = false; if (!clickable) { //点击的长按事件就是在这里执行的 checkForLongClick(0, x, y); break; } 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, x, y); } break; case MotionEvent.ACTION_CANCEL: if (clickable) { setPressed(false); } removeTapCallback(); removeLongPressCallback(); mInContextButtonPress = false; mHasPerformedLongPress = false; mIgnoreNextUpEvent = false; mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN; break; case MotionEvent.ACTION_MOVE: if (clickable) { drawableHotspotChanged(x, y); } // Be lenient about moving outside of buttons if (!pointInView(x, y, mTouchSlop)) { // Outside button // Remove any future long press/tap checks removeTapCallback(); removeLongPressCallback(); if ((mPrivateFlags & PFLAG_PRESSED) != 0) { setPressed(false); } mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN; } break; } return true; } return false; }
可以看到performClick(),这个方法中执行的就是点击事件。对于post()方法是如何执行的原理,下篇我们再来介绍。这里我们再来看看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; }
这里方法还是比较简单的,就是看看有没有设置点击事件,如果设置了就执行。这里有mListenerInfo,通过setOnClickListener()设置的回调就是在这里。至此,view事件的传递和犯法就分析完了。
总结:
1、执行流程:ViewRootImpl-->DecorView-->activity-->window-->DecorView(ViewGroup)-->View;
2、执行总线:dispatchTouchEvent(),view事件的分发就是一直在递归调用这个方法;
3、ViewGroup的dispatchTouchEvent()在进行事件分发的时候,会通过onInterceptTouchEvent()这个对事件进行拦截,当你想对事件进行拦截处理时,重写这个方法就可以了,如果子view不想分类进行拦截,那么可以调用getParnet().requestDisallowInterceptTouchEvent()请求父类不要对事件进行拦截,也就是父类不执行onInterceptTouchEvent()这个方法。
4、当事件分发到具体的某一个view时,不管是不是ViewGroup,最后执行的一定就是View这个类中的dispatchTouchEvent()方法,这里就是对事件的具体处理了,当然这个处理还是要我们自己去处理,Android只是执行了一个处理事件的顺序。
5、事件处理的顺序:
5.1、最先执行的是setOnTouchEvent()这个方法中的回调,如归这个回调中返回的true,那么View自身的 onTouchEvent就不会执行了,如果这个回调中返回的是false,那么View自身的onTouchEvent还是会执行的,
5.2、如果没有设置setOnTouchEvent()这个回调,那么就会执行View自身的onTouchEvent(),对于我们通过setOnClickListener()和setOnLongClickListener()设置的回调,就是在这个方法中执行到的。
6、对于我们设置的所有回调事件都是存到了ListenerInfo这个类中,这个类就是定义了一些事件回调的变量。