Android Touch事件分发详解

Android Touch事件分发详解

先说一些基本的知识,方便后面分析源码时能更好理解。 – 所有Touch事件都被封装成MotionEvent对象,包括Touch的位置、历史记录、第几个手指等.

事件类型分为ACTION_DOWN,ACTION_UP,ACTION_MOVE,ACTION_POINTER_DOWN,ACTION_POINTER_UP,ACTION_CANCEL, 每个 一个完整的事件以ACTION_DOWN开始ACTION_UP结束,并且ACTION_CANCEL只能由代码引起.一般对于CANCEL的处理和UP的相同。 CANCEL的一个简单例子:手指在移动的过程中突然移动到了边界外,那么这时ACTION_UP事件了,所以这是的CANCEL和UP的处理是一致的。

事件的处理分别为dispatchTouchEveent()分发事件(TextView等这种最小的View中不会有该方式)、onInterceptTouchEvent()拦截事件(ViewGroup中拦截事件)、onTouchEvent()消费事件.

事件从Activity.dispatchTouchEveent()开始传递,只要没有停止拦截,就会从最上层(ViewGroup)开始一直往下传递,,子View通过onTouchEvent()消费事件。(隧道式向下分发).

如果时间从上往下一直传递到最底层的子View,但是该View没有消费该事件,那么该事件会反序网上传递(从该View传递给自己的ViewGroup,然后再传给更上层的ViewGroup直至传递给Activity.onTouchEvent()). (冒泡式向上处理).

如果View没有消费ACTION_DOWN事件,之后其他的MOVE、UP等事件都不会传递过来.

事件由父View(ViewGroup)传递给子View,ViewGroup可以通过onInterceptTouchEvent()方法对事件进行拦截,停止其往下传递,如果拦截(返回true)后该事件 会直接走到该ViewGroup中的onTouchEvent()中,不会再往下传递给子View.如果从DOWN开始,之后的MOVE、UP都会直接在该ViewGroup.onTouchEvent()中进行处理。 如果子View之前在处理某个事件,但是后续被ViewGroup拦截,那么子View会接收到ACTION_CANCEL.

OnTouchListener优先于onTouchEvent()对事件进行消费。

TouchTarget是保存手指点击区域属性的一个类,手指的所有移动过程都会被它记录下来, 包含被touch的View。

废话不多说,直接上源码,源码妥妥的是最新版5.0: 我们先从Activity.dispatchTouchEveent()说起:

/** * 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. */(MotionEvent ev) {if (ev.getAction() == MotionEvent.ACTION_DOWN) {onUserInteraction();}if (getWindow().superDispatchTouchEvent(ev)) {return true;}return onTouchEvent(ev);}

代码一看能感觉出来DOWN事件比较特殊。我们继续走到onUserInteraction()代码中.

/** * Called whenever a key, touch, or trackball event is dispatched to the * activity. Implement this method if you wish to know that the user has * interacted with the device in some way while your activity is running. * This callback and {@link #onUserLeaveHint} are intended to help * activities manage status bar notifications intelligently; specifically, * for helping activities determine the proper time to cancel a notfication. * * <p>All calls to your activity’s {@link #onUserLeaveHint} callback will * be accompanied by calls to {@link #onUserInteraction}. This * ensures that your activity will be told of relevant user activity such * as pulling down the notification pane and touching an item there. * * <p>Note that this callback will be invoked for the touch down action * that begins a touch gesture, but may not be invoked for the touch-moved * and touch-up actions that follow. * * @see #onUserLeaveHint() */() {}

但是该方法是空方法,没有具体实现。 我们往下看getWindow().superDispatchTouchEvent(ev). getWindow()获取到当前Window对象,表示顶层窗口,管理界面的显示和事件的响应;每个Activity 均会创建一个PhoneWindow对象, 是Activity和整个View系统交互的接口,但是该类是一个抽象类。 从文档中可以看到The only existing implementation of this abstract class is android.policy.PhoneWindow, which you should instantiate when needing a Window., 所以我们找到PhoneWindow类,查看它的superDispatchTouchEvent()方法。

(MotionEvent event) {return mDecor.superDispatchTouchEvent(event);}

该方法又是调用了mDecor.superDispatchTouchEvent(event), mDecor是什么呢? 从名字中我们大概也能猜出来是当前窗口最顶层的DecorView, Window界面的最顶层的View对象。

// This is the top-level view of the window, containing the window decor.private DecorView mDecor;

讲到这里不妨就提一下DecorView.

{…}

它集成子FrameLayout所有很多时候我们在用布局工具查看的时候发现Activity的布局FrameLayout的。就是这个原因。 好了,我们接着看DecorView中的superDispatchTouchEvent()方法。

(MotionEvent event) {return super.dispatchTouchEvent(event);}

是调用了super.dispatchTouchEveent(),而DecorView的父类是FrameLayout所以我们找到FrameLayout.dispatchTouchEveent(). 我们看到FrameLayout中没有重写dispatchTouchEveent()方法,所以我们再找到FrameLayout的父类ViewGroup.看ViewGroup.dispatchTouchEveent()实现。 新大陆浮现了…

/** * {@inheritDoc} */(MotionEvent ev) {// Consistency verifier for debugging purposes.是调试使用的,我们不用管这里了。if (mInputEventConsistencyVerifier != null) {mInputEventConsistencyVerifier.onTouchEvent(ev, 1);}boolean handled = false;(onFilterTouchEventForSecurity(ev)) {action = ev.getAction();final int actionMasked = action & MotionEvent.ACTION_MASK;(actionMasked == MotionEvent.ACTION_DOWN) {cancelAndClearTouchTargets(ev);resetTouchState();// 如果是`Down`,那么`mFirstTouchTarget`到这里肯定是`null`.因为是新一系列手势的开始。// `mFirstTouchTarget`是处理第一个事件的目标。}intercepted;if (actionMasked == MotionEvent.ACTION_DOWN|| mFirstTouchTarget != null) {disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;if (!disallowIntercept) {// 判断该`ViewGroup`是否要拦截该事件。`onInterceptTouchEvent()`方法默认返回`false`即不拦截。intercepted = onInterceptTouchEvent(ev);ev.setAction(action); // restore action in case it was changed} else {// 子`View`通知父`View`不要拦截。这样就不会走到上面`onInterceptTouchEvent()`方法中了,// 所以父`View`就不会拦截该事件。intercepted = false;}} else {intercepted = true;}canceled = resetCancelNextUpFlag(this)|| actionMasked == MotionEvent.ACTION_CANCEL;split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;// 保存当前要分发给的目标TouchTarget newTouchTarget = null;boolean alreadyDispatchedToNewTouchTarget = false;// 如果没取消也不拦截,进入方法内部if (!canceled && !intercepted) {// 下面这部分代码的意思其实就是找到该事件位置下的`View`(可见或者是在动画中的View), 并且与`pointID`关联。if (actionMasked == MotionEvent.ACTION_DOWN|| (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)|| actionMasked == MotionEvent.ACTION_HOVER_MOVE) {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);ArrayList<View> preorderedList = buildOrderedChildList();final boolean customOrder = preorderedList == null&& isChildrenDrawingOrderEnabled();// 遍历找子`View`进行分发了。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);(!canViewReceivePointerEvents(child)|| !isTransformedTouchPointInView(x, y, child, null)) {continue;}// 找到该`View`对应的在`mFristTouchTarget`中的存储的目标, 判断这个`View`可能已经不是之前`mFristTouchTarget`中的`View`了。// 如果找不到就返回null, 这种情况是用于多点触摸, 比如在同一个`View`上按下了多跟手指。newTouchTarget = getTouchTarget(child);if (newTouchTarget != null) {newTouchTarget.pointerIdBits |= idBitsToAssign;// 找到该View了,不用再循环找了break;}resetCancelNextUpFlag(child);(dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {// 如果这个Child View能分发,那我们就要把之前存储的值改变成现在的Child View。// Child wants to receive touch within its bounds.mLastTouchDownTime = ev.getDownTime();if (preorderedList != null) {// childIndex points into presorted list, find original indexfor (int j = 0; j < childrenCount; j++) {if (children[childIndex] == mChildren[j]) {mLastTouchDownIndex = j;break;}}} else {mLastTouchDownIndex = childIndex;}mLastTouchDownX = ev.getX();mLastTouchDownY = ev.getY();// 赋值成现在的Child View对应的值,并且会把`mFirstTouchTarget`也改成该值(mFristTouchTarget`与`newTouchTarget`是一样的)。newTouchTarget = addTouchTarget(child, idBitsToAssign);// 分发给子`View`了,不用再继续循环了alreadyDispatchedToNewTouchTarget = true;break;}}if (preorderedList != null) preorderedList.clear();}// `newTouchTarget == null`就是没有找到新的可以分发该事件的子`View`,那我们只能用上一次的分发对象了。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;}}}(mFirstTouchTarget == null) {handled = dispatchTransformedTouchEvent(ev, canceled, null,TouchTarget.ALL_POINTER_IDS);} else {TouchTarget predecessor = null;TouchTarget target = mFirstTouchTarget;while (target != null) {final TouchTarget next = target.next;// 找到了新的子`View`,并且这个是新加的对象,上面已经处理过了。if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {handled = true;} else {cancelChild = resetCancelNextUpFlag(target.child)|| intercepted;// 正常分发if (dispatchTransformedTouchEvent(ev, cancelChild,target.child, target.pointerIdBits)) {handled = true;}// 如果是onInterceptTouchEvent返回true就会遍历mFirstTouchTarget全部给销毁,这就是为什么onInterceptTouchEvent返回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) {actionIndex = ev.getActionIndex();final int idBitsToRemove = 1 << ev.getPointerId(actionIndex);removePointersFromTouchTargets(idBitsToRemove);}}if (!handled && mInputEventConsistencyVerifier != null) {mInputEventConsistencyVerifier.onUnhandledEvent(ev, 1);}return handled;}然后继续努力,把让自己跌倒的石头搬掉或绕过去,不就解决问题了吗?

Android Touch事件分发详解

相关文章:

你感兴趣的文章:

标签云: