Touch事件在viewGroup中的运转及总结

前面总结了touch事件在View中的传递,以及在一个viewTree中传递的流程。

但是在ViewGroup以及ViewTree中的传递是根据log看出来的,那么在代码中到底是如何处理的

今天就看下代码,主要就是从viewGroup中dispatchEvent开始。

首先还是会调用当前activity的dispatchTouchEvent();然后走走走,...
就走到了rootView的dispatchTouchEvent();--并且rootView还是viewGroup

先上代码,随后慢慢分析。

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
        }

        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;
            }

            // 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 (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 (childrenCount != 0) {
                        // Find a child that can receive the event.
                        // Scan children from front to back.
                        final View[] children = mChildren;
                        final float x = ev.getX(actionIndex);
                        final float y = ev.getY(actionIndex);

                        for (int i = childrenCount - 1; i >= 0; i--) {
                            final View child = children[i];
                            if (!canViewReceivePointerEvents(child)
                                    || !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();
                                mLastTouchDownIndex = i;
                                mLastTouchDownX = ev.getX();
                                mLastTouchDownY = ev.getY();
                                newTouchTarget = addTouchTarget(child, idBitsToAssign);
                                alreadyDispatchedToNewTouchTarget = true;
                                break;
                            }
                        }
                    }

                    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;
    }

下面就逐步分析这个代码,我们分阶段来看,有些细节就不说了。

首先是

 if (mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
        }
这个变量mInputEventConsistencyVerifier是View.java中的,找到后代码如下

	 /**
     * Consistency verifier for debugging purposes.
     * @hide
     */
    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
                    new InputEventConsistencyVerifier(this, 0) : null;
也就是为了debug做的一致性检验,我们这里可以不考虑。


然后就来到了下一步:

 if (onFilterTouchEventForSecurity(ev)) {
		   //判断是不是需要将事件安全过滤,一般返回true不用过滤,不过当touch模糊或者当前window模糊时会过滤掉
		   //如果过滤掉,则直接执行到下面这一行:
			 if (!handled && mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onUnhandledEvent(ev, 1);
        }
        return handled;
如果 是需要过滤掉的事件(一般不会),那代码就直接走到了下面这一步

	 if (!handled && mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onUnhandledEvent(ev, 1);
        }
        return handled;
也就是取消debug,然后返回handled,而handled默认为false,所以 等于啥都没做就返回了false,

事件就传递给了activity的onTouchEvent了。
注意,事件一旦由activity的dispatchTouchEvent传递给Activity的onTouchEvent后,

那么这一次事件中的所有活动就直接是由Activity的dispatchTouchEvent到Activity的onTouchEvent了


那么如果按正常情况,是可以进行事件传递的,代码如下

  final int action = ev.getAction();
            final int actionMasked = action & MotionEvent.ACTION_MASK;
首先是得到这次事件的活动,与 MotionEvent.ACTION_MASK相与
MotionEvent.ACTION_MASK是255,255与任何数相与都是那个数本身,
因此actionMasked也就是action。

代码继续往下走:

// 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();
            }
  如果actionMasked为按下,则重置此前的所有操作,重置为初始状态。

具体实现了什么暂时不用深究,反正知道当按下后就是世界的重新开始了,

android中是可以重来的(多美好),最重要的就是将mFirstTouchTarget置为了null


代码继续往下走

 // 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;
            }

注释说的很明白,就是是否进行拦截的一个判断
因为是按下,所以actionMasked == MotionEvent.ACTION_DOWN为true.
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
 
FLAG_DISALLOW_INTERCEPT是横为true的,mGroupFlags这个的值由什么决定
由它的这个viewTree中的子view的方法
child.getParent().requestDisallowInterceptTouchEvent(true);

参数为true,则FLAG_DISALLOW_INTERCEPT。
因此因此,当你的子view不想让父view拦截时,也可以不重写父view的方法,而是直接调用
getParent().requestDisallowInterceptTouchEvent(true);就可以了


进行了disallowIntercept赋值后,代码继续往下走

如果disallowIntercept = false.则进入第一层

intercepted = onInterceptTouchEvent(ev);
ev.setAction(action); // restore action in case it was changed
 在这里就执行了onInterceptedTouchEvent,默认返回false,

我们可以重写返回true,则intercepted就为true,这就是拦截的标记
 默认viewGroup中是不拦截的

如果disallowIntercept = true,则直接默认不拦截

如果如果if (actionMasked == MotionEvent.ACTION_DOWN
                  || mFirstTouchTarget != null) {

这一层不满足,也就是说不是按下,并且mFirstTouchTarget==null
那么

else {
                // There are no touch targets and this action is not an initial down
                // so this view group continues to intercept touches.
                intercepted = true;
            }

也就是拦截,这个就是解释 如果第一次拦截了(就没有touchTARGET,mFirstTouchTarget==null),

那么在这次事件中的以后就都拦截,并且不走onIntercepetTouchEvent了
但重新开始down,这些又会重新判断


第三部分,现在intercepted这个标志决定了,也知道了onInterceptTouchEvent是什么时候执行的

我们看下面做什么

先是不是特别重要的代码块:就是判断是不是取消手势或其他,然后到了下面

 if (!canceled && !intercepted) {
//首先肯定不是cancel的手势,那!canceled就为true,主要就是判断!intercepted的值了,这个值在上面决定过
		   
//如果interctepted为true,则就是说父控件拦截,那么按理论是直接执行父控件的onTouch事件,我们看代码来查看是怎样做到的
		   
// 拦截,不走if,就跳到了下面
		  
	// 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 {
			...
注意注意,到这时我们还没给mFirstTouchTarget赋值,因此它就是null的,

就走了if,执行了dispatchTransformedTouchEvent(ev, canceled, null,TouchTarget.ALL_POINTER_IDS);

先上这个方法的完整代码

<span style="color:#333333;">  /**
     * Transforms a motion event into the coordinate space of a particular child view,
     * filters out irrelevant pointer ids, and overrides its action if necessary.
     * If child is null, assumes the MotionEvent will be sent to this ViewGroup instead.
     */
    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);
            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;
        }

        // 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;
    }</span><span style="color:#ff0000;">
</span>


我们看这个方法里主要做了什么,基本上viewTree中事件的分发都和这个方法有关,这个方法非常重要
上面是这个方法的所有,那么我们在这时调用这个方法,我们要走下这个方法的流程了

if (cancel || oldAction == MotionEvent.ACTION_CANCEL) {
			//第一个cancel是传递过来的,而传时这个cancel的值也是是否取消手势有关,因为不是,所以就不走if,走到了下面
			
			if (newPointerIdBits == oldPointerIdBits) {
            if (child == null || child.hasIdentityMatrix()) {
                if (child == null) {
                    handled = super.dispatchTouchEvent(event);
                }
第一个if()
newPointerIdBits = oldPointerIdBits & desiredPointerIdBits;
desiredPointerIdBits传过来的是TouchTarget.ALL_POINTER_IDS---从名字看是所有,就是都为各个位都为1 
 任何一个数与这样的数相与都为本身,因此old=true,因此第一个if成立
走第二个if
child是传过来的值,确实为null
因此就走了super.dispatchTouchEvent(event)


 注意,此时的super是指类的继承关系中的super,也就是viewGroup的父类view的dispatchTouchEvent,

不是viewTree中child和parent,要分清



那么就走到了view.dispatchTouchEvent,那么狠清楚了,走到了我们上一次所说的
也就是onDispatch--onTOUCH--ONTouchEvent---onclick()
这个是在当前viewGroup这一层执行的,因此也就执行了


viewGroup的onTouch方法(也就是view的),如果不消费,就返回给上一层,让上一层执行onTouchEvent了

然后就返回handled,这个handled的值就是由view的dispatchTouchEvent决定的。


那么那么,如果Intercept为false,也就是不拦截,就进入了

//那么那么,如果Intercept为false,也就是不拦截,就进入了
if (!canceled && !intercepted) {//中,那按情况是执行子view的dispatchTouchEvent,将事件分发下去,那么是怎么做到的,看代码
			//if代码块中
	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;
				//得到这次事件的索引以及索引对应的fingerID
				
			 final int childrenCount = mChildrenCount;//得到当前viewGroup的子view数量
				 if (childrenCount != 0) {
                        // Find a child that can receive the event.
                        // Scan children from front to back.
                        final View[] children = mChildren;
                        final float x = ev.getX(actionIndex);
                        final float y = ev.getY(actionIndex);
				
				//如果子view数量不为0,就记录下这次事件的坐标。
				
				for (int i = childrenCount - 1; i >= 0; i--) {
                            final View child = children[i];
                            if (!canViewReceivePointerEvents(child)
                                    || !isTransformedTouchPointInView(x, y, child, null)) {
                                continue;
                            }
		//对这些子view进行循环,判断当前事件坐标是不是在这个子view中,如果不是,就继续循环

下面是如果是的代码

关键的在这

 if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
                                // Child wants to receive touch within its bounds.
                                mLastTouchDownTime = ev.getDownTime();
                                mLastTouchDownIndex = i;
                                mLastTouchDownX = ev.getX();
                                mLastTouchDownY = ev.getY();
                                newTouchTarget = addTouchTarget(child, idBitsToAssign);
                                alreadyDispatchedToNewTouchTarget = true;
                                break;
                            }
又是这个方法,dispatchTransformedTouchEvent,但是这次走的我们要看下是怎么走的

根据参数走到了这边

 // 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);
        }
hild是不为空的,那么就到了这一句
handled = child.dispatchTouchEvent(transformedEvent);--开始执行了子child的dispatchTouchEvent,将handled返回!
这样就将事件传递给子view或者子viewGroup了


下面还有一些事件的分发细节,今天暂不说了,这个代码很复杂,考虑的很多,

主要就是根据源码有一个印象关于事件传递


那需要最后总结下了

当在一个屏幕上down时

activity.dispatchTouchEvent()--rootView.dispatchTouchEvent()




没有getParent.requestDisallowInterceptTouchEvent(true).并且onIntercpetTouchEvent返回为false(默认)
childView.dispatchTouchEvent()--...--最后一个childView.dispatchTouchEvent--childView.onTouchEvent()
如果childView.onTouchEvent返回true,则消费了事件,事件就到此终止了。
如果childView.onTouchEvent返回false,则响应事件,则不消费事件,事件又向他的父view传递,调用父view.onTouchEvent,重复上述行为
直到到了
rootView.onTouchEvent();



如果设置了getParent.requestDisallowInterceptTouchEvent(true)或者onIntercpetTouchEvent返回true
则直接执行rootView.onTouchEvent();


如果rootView.onTouchEvent()返回false,则整个viewTree中没有任何事件的消费,
就又返回到了activity中的onTouchEvent();
那这个是时候进行up操作,就不在执行view事件传递了!直接就由
activity.dispatchTouchEvent()--activity.onTouchEvent().直到下一次事件的开始。。
framework层的探测很懒惰,第一次不消费,就再不问你们是否消费了。



以上是分析,在实际中基本就是这个流程,最后推荐如果更清楚的搞清这个传递,看下面链接视频

http://v.youku.com/v_show/id_XODQ1MjI2MDQ0.html?f=23088492






你可能感兴趣的:(Touch事件在viewGroup中的运转及总结)