-
概述
手指触摸事件是由InputManagerService服务来监听并发送到对应窗口的对应Activity的,大体来说就是该服务会监听设备的各种输入事件,然后会有一个InputEventReceiver来接收事件变化,然后发送给Activity或Dialog,这部分是C/C++部分完成的,我们这里先只分析用户层的分发机制。
-
Activity
根据上面的信息,我们以Activity的dispatchTouchEvent方法作为事件入口。
在开始之前,我们要先有一个概念:dispatchTouchEvent方法的返回值为 true表示尝试自己消费(只是尝试)而不往下分发,返回false表示继续往下分发,Activity的这个逻辑同样在更上一级的Framework层。
public boolean dispatchTouchEvent(MotionEvent ev) { if (ev.getAction() == MotionEvent.ACTION_DOWN) { onUserInteraction(); } if (getWindow().superDispatchTouchEvent(ev)) { return true; } return onTouchEvent(ev); }
onUserInteraction没有默认实现,暂不考虑。可以看到,这里会调用getWindow().superDispatchTouchEvent(ev)方法判断是返回true还是返回onTouchEvent方法的返回值。getWindow方法获取的就是PhoneWindow:
@Override public boolean superDispatchTouchEvent(MotionEvent event) { return mDecor.superDispatchTouchEvent(event); }
PhoneWindow的mDecor就是DecorView:
public boolean superDispatchTouchEvent(MotionEvent event) { return super.dispatchTouchEvent(event); }
DecoView继承自ViewGroup,所以调用的就是ViewGroup的dispatchTouchEvent方法,也就是分发给子View们优先尝试捕获,下面会说到。
如果子View的询问中有捕获的则会返回true,这一点在ViewGroup的dispatchTouchEvent分析中会看到,则这里也会返回true通知上一级已经消费事件;如果子View中没有捕获该事件,则会调用Activity本身的onTouchEvent方法:
public boolean onTouchEvent(MotionEvent event) { if (mWindow.shouldCloseOnTouch(this, event)) { finish(); return true; } return false; }
这里会返回false,默认不消费。
而Activity中是没有onInterceptTouchEvent方法的。
-
ViewGroup
下面贴出dispatchTouchEvent的部分代码:
@Override public boolean dispatchTouchEvent(MotionEvent ev) { // 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; //onFilterTouchEventForSecurity判断是否view已显示 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. //注意这里,当事件是第一次按下或者之前有消费者消费了事件时才会重新调用onInterceptTouchEvent判断是否拦截,否则一律拦截,这就表示如果ACTION_DOWN有拦截了那么后面的ACTION_MOVE和ACTION_UP等事件就不会再判断了,直接拦截 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 isMouseEvent = ev.getSource() == InputDevice.SOURCE_MOUSE; final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0 && !isMouseEvent; TouchTarget newTouchTarget = null; boolean alreadyDispatchedToNewTouchTarget = false; if (!canceled && !intercepted) { // If the event is targeting accessibility 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 = isMouseEvent ? ev.getXCursorPosition() : ev.getX(actionIndex); final float y = isMouseEvent ? ev.getYCursorPosition() : 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; for (int i = childrenCount - 1; i >= 0; i--) { final int childIndex = getAndVerifyPreorderedIndex( childrenCount, i, customOrder); final View child = getAndVerifyPreorderedView( preorderedList, children, childIndex); if (!child.canReceivePointerEvents() || !isTransformedTouchPointInView(x, y, child, null)) { 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; }
ACTION_DOWN事件时会调用resetTouchState方法:
private void resetTouchState() { clearTouchTargets(); resetCancelNextUpFlag(this); mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT; mNestedScrollAxes = SCROLL_AXIS_NONE; }
可以看到,这里的mGroupFlags会移除FLAG_DISALLOW_INTERCEPT标签,所以disallowIntercept是false,所以intercepted等于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; }
这里的默认实现中只要是touch事件都会返回false,表示不会拦截。
接下来会判断事件是否取消,如果既没有取消,intercepted又为false,则会进入if (!canceled && !intercepted) 代码块中。这个代码块中做了什么呢?
通过buildTouchDispatchChildList方法找出所有的子View:
ArrayList<View> buildOrderedChildList() { final int childrenCount = mChildrenCount; if (childrenCount <= 1 || !hasChildWithZ()) return null; if (mPreSortedChildren == null) { mPreSortedChildren = new ArrayList<>(childrenCount); } else { // callers should clear, so clear shouldn't be necessary, but for safety... mPreSortedChildren.clear(); mPreSortedChildren.ensureCapacity(childrenCount); } final boolean customOrder = isChildrenDrawingOrderEnabled(); for (int i = 0; i < childrenCount; i++) { // add next child (in child order) to end of list final int childIndex = getAndVerifyPreorderedIndex(childrenCount, i, customOrder); final View nextChild = mChildren[childIndex]; final float currentZ = nextChild.getZ(); // insert ahead of any Views with greater Z int insertIndex = i; while (insertIndex > 0 && mPreSortedChildren.get(insertIndex - 1).getZ() > currentZ) { insertIndex--; } mPreSortedChildren.add(insertIndex, nextChild); } return mPreSortedChildren; }
可以看到,这里会按照子View的z坐标进行排序,z坐标越大的会放在集合靠后的位置,即在View层级中越往上的View放在集合中较后的位置。
然后会执行for 循环:for (int i = childrenCount - 1; i >= 0; i--)。可见这里会先询问层级靠上的View。
child.canReceivePointerEvents方法验证View是否可见或者应用了动画,这里也可以解释位移View动画中原先的位置为何能响应点击事件;isTransformedTouchPointInView表示View是否从原先的位置位移到了此时点击触摸点的位置。这里的意义就是排除不可见、无动画且非移动到触摸点的View,缩小事件分发范围。
然后,getTouchTarget(child)方法会获取消费事件的View:
private TouchTarget getTouchTarget(@NonNull View child) { for (TouchTarget target = mFirstTouchTarget; target != null; target = target.next) { if (target.child == child) { return target; } } return null; }
这里我们是ACTION_DOWN事件,所以此时取到的这个newTouchTarget是null。
接着会调用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) { //如果ViewGroup中判断此时是事件取消了,则event会保存这个取消状态 event.setAction(MotionEvent.ACTION_CANCEL); //因为此时是取消状态,child如果为空则交给这里的父容器本身尝试去处理,因为super调用的就是View的dispatchTouchEvent方法,那个方法里只会分发和View本身相关的 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; } final MotionEvent transformedEvent; if (newPointerIdBits == oldPointerIdBits) { if (child == null || child.hasIdentityMatrix()) { if (child == null) { handled = super.dispatchTouchEvent(event); } else { //hasIdentityMatrix会判断是否产生过偏移 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; } //如果两次事件触摸点前后没发生变化则使用之前的event(主要是getPointerIdBits获取的值还能继续用) transformedEvent = MotionEvent.obtain(event); } else { //如果两次事件触摸点前后发生变化了就替换成新的触摸点id 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; }
可以看到,这个方法里会尝试在子View中找到消费事件的View,如果返回true表示找到了,那么此时会记录mLastTouchDownIndex、mLastTouchDownX和mLastTouchDownY,alreadyDispatchedToNewTouchTarget在这里置为true,然后会break跳出循环。而newTouchTarget会通过addTouchTarget方法生成:
private TouchTarget addTouchTarget(@NonNull View child, int pointerIdBits) { final TouchTarget target = TouchTarget.obtain(child, pointerIdBits); target.next = mFirstTouchTarget; mFirstTouchTarget = target; return target; }
然后在接下来的判断中,mFirstTouchTarget不等于null,alreadyDispatchedToNewTouchTarget等于true,mFirstTouchTarget就是我们在上面询问中捕获到的消费者,这些条件都成立了,所以handled赋值为true,最后返回handled。
ACTION_DOWN事件走完之后我们看接下来的MOVE和UP事件会不会有什么变化。
DOWN事件流程中我们如果捕获了一个消费者,那么getTouchTarget方法获取的newTouchTarget就不会为null了:
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; }
所以这里会直接break,并不会再次执行dispatchTransformedTouchEvent方法尝试捕获,那我们的MOVE和UP事件在哪里分发的呢?上面我们说到根据alreadyDispatchedToNewTouchTarget为true来直接给handled赋值为true,alreadyDispatchedToNewTouchTarget只在一个地方赋值为true的,那就是for循环捕获消费者的时候,dispatchTransformedTouchEvent方法返回true时,那这里我们没有去重新捕获消费者(因为我们之前捕获到了),所以alreadyDispatchedToNewTouchTarget是false,那么在最后的while代码中的alreadyDispatchedToNewTouchTarget判断中会走else分支,在这里会再次调用dispatchTransformedTouchEvent方法分发事件,如果返回true表示分发成功,那么handled赋值为true返回。
所以dispatchTouchEvent方法中总共有两处调用dispatchTransformedTouchEvent方法的地方,第一次调用除了分发事件,分发事件成功(即返回true)时还会保存消费者对象,同时会保存一个标志位alreadyDispatchedToNewTouchTarget为true,表示已经分发过了,这样在最后的while代码块中会跳过dispatchTransformedTouchEvent方法的第二次调用,所以alreadyDispatchedToNewTouchTarget保证了不会重复分发两次,即这两处调用是互斥的;第二次调用只是单纯地分发事件,和它关联的逻辑只有修改handled为true。
在最后会判断如果事件取消了或者手指抬起了则会调用resetTouchState方法,这样mFirstTouchTarget就又置为空了,所以下次按下又会重新走之前的逻辑。
综上所知,在触摸事件第一次触发的时候会分发事件并保存消费者(如果分发成功的话),在本次事件结束之前(取消或者手指抬起),DOWN事件之后的类型分发并不会再次去找新的消费者,都会直接分发到之前已经消费了DOWN事件的child,也就是说,我们从手指按下到抬起,这其中的的DOWN、MOVE和UP等类型的分发都会被同一个View消费。
ViewGroup中则没有重写onTouchEvent方法,至于为什么你可以好好理解一下,因为如果ViewGroup作为一个消费者的时候(上面的super.dispatchTouchEvent方法返回true)它其实就是一个View的身份,因为消费者消费的肯定是和自身相关的逻辑,这和子View无关,只有当它要分发事件的时候它才作为一个ViewGroup的身份去处理的。
-
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; }
onFilterTouchEventForSecurity方法我们前面说过了,如果View没有隐藏则返回true,所以成立。
然后会判断是否通过setOnTouchListener方法设置过OnTouchListener,如果设置过,则调用他的onTouch方法,如果onTouch方法返回true则表示已消费。
接着判断,如果之前onTouch方法返回了true的话,这里的result是true,则不会执行到本身的onTouchEvent方法,这里可以得知,OnTouchListener会优先尝试执行,如果OnTouchListener的onTouch方法返回了true则不会再去调用onTouchEvent方法;若是OnTouchListener的onTouch方法返回了false,则会根据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(); //判断是否可以点击 final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE; //TouchDelegate用来设置比View本身更大区域的事件捕获,作用是把溢出View边界的event的location修改到View内 if (mTouchDelegate != null) { if (mTouchDelegate.onTouchEvent(event)) { return true; } } //如果clickable为false,则View不会执行下面的逻辑 if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) { ... ... return true; } return false; }
这个方法比较冗长,只贴了部分关键代码.
可以看到,这里只要是clickable为true,onTouchEvent方法都会返回true,否则会返回false。
-
总结
现在我们来总结一下Android的事件分发机制:
- 从Activity的dispatchTouchEvent方法开始,调用PhoneWindow的superDispatchTouchEvent方法尝试往下分发,如果这个方法返回true,说明子View中有组件消费了,那么这里会返回true给Framework层表示已消费。如果子View中没有组件消费该事件,则会调用Activity本身的onTouchEvent方法,默认会返回false;
- PhoneWindow的superDispatchTouchEvent方法调用了DecorView的superDispatchTouchEvent方法,这里又调用了super的dispatchTouchEvent方法,DecorView继承自ViewGroup,所以就走到了ViewGroup的dispatchTouchEvent方法;
- ViewGroup的dispatchTouchEvent方法中会把所有的View按照z坐标排序,z坐标越大的放在集合后面,然后从末端开始循环这个集合,这表示会先尝试分发给最内层的View,因为View的添加顺序都是最后添加的View在最上层,所以它的z坐标是最大的,也就是说最上层的View就是最内层的View,如果找到了消费事件的View则保存这个消费对象为mFirstTouchTarget,然后跳出循环;
- ACTION_DOWN类型事件处理之后,后面跟随的MOVE或UP等事件会自动交给之前保存的mFirstTouchTarget指向的View来消费,直到新一轮的触摸事件开始;
- 第3步中是调用的dispatchTransformedTouchEvent方法来查找可消费View的,第3条只是说明了大体的流程,细节就是,在这个方法内部会调用每一个合法child的dispatchTouchEvent方法,如果child还是ViewGroup的话就会走该child的分发工作,原理和上述一样,相当于递归,不过是更内部一层ViewGroup的事件分发,如果child是View的话就会走View的dispatchTouchEvent逻辑;
- ViewGroup的dispatchTouchEvent方法的工作是向子View分发事件的,而View的dispatchTouchEvent方法则是用来决定它内部是要通过什么途径来消费事件,首先会先尝试调用OnTouchListener的onTouch方法(如果OnTouchListener不为空的话),如果onTouch方法返回了true,则View的onTouchEvent方法不会执行,否则会调用onTouchEvent方法,这两处处理有一个返回true则dispatchTouchEvent就返回true;
- View的onTouchEvent方法中就是处理ACTION_DOWN、ACTION_UP等具体的事件了,值得注意的是我们添加的OnClickListener是在这里尝试判断执行的。
总的来说,一次触摸事件从ACTION_DOWN开始,事件会从最上面的Activity开始尝试分发,如果中间某个ViewGroup拦截了的话就在该ViewGroup内部消费,如果没被拦截则会一直走到最内层的子View,如果最内层的子View没有消费该事件则会一层一层地往父容器上面分发,最终如果都没有捕获该事件则交给Activity的onTouchEvent方法,这个方法默认返回false,所以最终没消费的话会再往上交给最初事件分发者。如果在以上分发过程中有View消费了该事件,则会记住该View,ACTION_DOWN之后的ACTION_MOVE、ACTION_UP等事件会直接分发给该View处理,直到新一次的ACTION_DOWN开始会重新走分发逻辑。
网友评论