Android触控事件分发详解-基本流程
来源:互联网 发布:微信跳淘宝 编辑:程序博客网 时间:2024/06/06 02:57
在写自定义控件和处理滑动冲突的时候,经常会需要处理触控事件,很多网上博文的基本套路就是在各个触控事件相关的函数里做一下log看一下先后顺序,然后猜出个基本流程,诚然是八九不离十,不过还是有一些偏差,在这里整理一下网上看到的比较正确的文章和一些阅读Android源码的理解(所有贴的源码基于API 24)。
涉及到触控事件分发的方法有三个:dispatchTouchEvent(), onInterceptTouchEvent(), onTouchEvent()
其中,Activity和View只有dispatchTouchEvent()和onTouchEvent(),ViewGroup还有onInterceptTouchEvent()。
对于一次屏幕的触控操作,可以简要的分为三个阶段(暂且不说多点触控):手指按下,移动,抬起,这三个阶段也被描述为三个触控事件即:ACTION_DOWN,ACTION_MOVE,ACTION_UP;一次完整的屏幕触控操作就可以被这三个触控事件描述为一个事件序列:ACTION_DOWN → ACTION_MOVE → ...... → ACTION_MOVE → ACTION_UP。这个序列被封装在MontionEvent中,传递给各个负责事件分发的方法。
先放上自己整理的事件分发整体流程图:
一个Touch事件发生时,最先由当前的Activity接收到,Activity通过dispatchTouchEvent()决定事件传递,先来看一下Activity的dispatchTouchEvent()的源码:
/** * Called to process touch screen events. You can override this to * intercept all touch screen events before they are dispatched to the * window. Be sure to call this implementation for touch screen events * that should be handled normally. * * @param ev The touch screen event. * * @return boolean Return true if this event was consumed. */ public boolean dispatchTouchEvent(MotionEvent ev) { if (ev.getAction() == MotionEvent.ACTION_DOWN) { onUserInteraction(); } if (getWindow().superDispatchTouchEvent(ev)) { return true; } return onTouchEvent(ev); }
可以看到在dispatchTouchEvent中,首先响应了ACTION_DOWN事件,通过追踪getWindow().superDispatchTouchEvent(ev)可以得知Activity在这里将touch事件传递给了DecorView,然后传递到当前的布局之中。之后通过阅读ViewGroup的dispatchTouchEvent()和View的dispatchTouchEvent()可以得知,dispatchTouchEvent的返回值,主要是用来给上一级确定是否消费此事件,如果return true,则事件被当前View消费,如果为false,则事件没有被消费,事件将交由上级的onTouchEvent()处理,整个事件分发的过程是在dispatchTouchEvent之中处理的。因此在重写dispatchTouchEvent()时,如果不写super.dispatchTouchEvent(),那么触控事件相当于被吞掉了,是不会继续传递的。
在ViewGroup的dispatchEvent中就可以看到onInterceptTouchEvent()相关的处理了:
@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 = 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; } } } // 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; }
其中的disallowIntercept值可以通过requestDisallowInterceptTouchEvent()方法来设置,告诉父View不要拦截,这样就不会触发onInterceptTouchEvent(),在ACTION_DOWN时,onInterceptTouchEvent()的返回值决定了当前ViewGroup是否拦截,如果决定拦截,则一个事件序列后续的touch事件都不会再继续分发,也不会经过onInterceptTouchEvent()。但是如果ACTION_DOWN时没有拦截,则会在最后分发事件的时候判断是否cancel,如果拦截,则向子View发送ACTION_CANCEL。
在dispatchTouchEvent()中可以得知,如果一个ViewGroup没有任何子View,或者决定拦截触控事件,那么它处理Touch消息跟普通View处理Touch消息一致(调用super.dispatchTouchEvent()即View的dispatchTouchEvent())。可以看看View的dispatchTouchEvent()是如何实现的:
/** * Pass the touch screen motion event down to the target view, or this * view if it is the target. * * @param event The motion event to be dispatched. * @return True if the event was handled by the view, false otherwise. */ 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; }
可以看到用户设置的onTouchListener是先于onTouchEvent()执行的,而且如果onTouchListener返回true,意味着事件已经被消费,onTouchEvent()就不会执行了。
在大概看完这三个函数之后可以分析出Android触控事件响应的一个基本流程:
- 触控事件从Activity的dispatchTouchEvent开始分发,随后进入布局并开始逐级向下传递,分发操作全部在dispatchTouchEvent方法内进行。dispatchTouchEvent()的返回值确定了这个事件有没有被消费,而事件有没有被消费由onTouchEvent()、onTouchListener.onTouch()等方法的返回值决定。
- 如果事件传递到最底层的View,但是该View没有消费事件,则事件会反序向上传递,直至传递给Activity。
- 如果View没有消费ACTION_DOWN事件,则不会接收到后续事件。
- 如果onIntercentTouchEvent()拦截了ACTION_DOWN,则后续事件不会再通过onInterceptTouchEvent(),如果没有拦截ACTION_DOWN但是后续事件被拦截,则子View会收到ACTION_CANCEL。
- onTouchListener.onTouch() 优先于 onTouchEvent()执行,且如果onTouchListener.onTouch()返回true则onTouchEvent()不会执行。
- Android触控事件分发详解-基本流程
- Android事件分发基本流程
- android事件分发流程
- Android事件分发流程
- android 事件分发流程
- Android事件分发流程
- Android事件分发流程
- Android事件分发详解
- Android 事件分发详解
- Android事件分发流程解析
- 图解Android事件分发流程
- Android点击事件分发流程
- Android焦点分发基本流程
- Android 事件分发机制详解
- Android事件分发机制详解
- Android事件分发机制详解
- Android Touch事件分发详解
- Android 事件分发机制详解
- Java 8 新特性
- Java MySQL 连接
- 人生之路
- 一个超好的命令行串口软件 --- PowerCmd --- 汉化破解版
- DRF depth=1的情况下对象的创建与更新问题
- Android触控事件分发详解-基本流程
- 如何实现FTP上传
- 素数环 题解
- Python爬虫基础
- 1478 括号序列的最长合法子段
- MFC xp style界面
- Unity Editor 编辑器扩展三 Unity Editor 数据持久化及Editor窗口的初识
- 作为一个新人,怎样学习嵌入式Linux?
- git命令上传本地项目至GitHub