码迷,mamicode.com
首页 > 其他好文 > 详细

onInterceptTouchEvent 与 onTouchEvent 分析与MotionEvent在ViewGroup与View中的分发

时间:2015-07-16 17:03:46      阅读:311      评论:0      收藏:0      [点我收藏+]

标签:onintercepttoucheven   ontouchevent   motionevent的分发   

onInterceptTouchEvent 与 onTouchEvent 分析与MotionEvent在ViewGroup与View中的分发

       Notice:本文将紧接着
这一片博文来分析,如果您还没有读过这一片博文,强烈建议你先读一次上述博文


     OK,言归正传,我们开始吧
      最近,一直听到有人在争论关于dispatchTouchEvent这个函数 和 onInterceptTouchEvent这两个函数到底是那一这真正的决定了MotionEvent的分发。这里我还是统一给出答案吧。我们都知道如果我们不希望我们的ViewGroup阻拦我们的View获得MotionEvent,我们一般只需要在onInterceptTouchEvent这个函数中return false(并且该函数默认return false)。或者,在特定的情况下,如果我们希望某些时候交给我们的我们ViewGroup来处理有些情况下我们又希望我们的View来处理MotionEvent。这种情况下,我们应该怎么来处理呢。我想大家都知道,我们需要在onInterceptTouchEvent做一些处理,因为大家都知道onInterceptTouchEvent是用来做MotionEvent事件的处理对象判断的。

    那么,答案很明显了,处理MotionEvent只有dispatchTouchEvent(其实这一点从函数名称都可以看出来,更不要说onInterceptTouchEvent还只是ViewGroup特有的方法)。

    好,我们先来整理我们目前已知的,并且提出疑问然后再开始分析
 
    一、Android 中的MotionEvent事件分发处理是由dispatchTouchEvent来完成的(底层直接调用该方法,我们这里不分析)
  
    二、通过上一篇博文我们知道dispatchTouchEvent > onTouch > onTouchEvent > onClick
            这里我还是简单啰嗦一下吧,其实onTouchListener 和 onClickListener 只是为了提供给上层便捷的处理接口,他们的存在只是为了对于开发提供了便捷,但是在Android中我们通常采用onInterceptTouchEvent和onTouchEvent 联合来判断MotionEvent的处理对象

    三、我们在ViewGroup中采用onInterceptTouchEvent和onTouchEvent 联合来判断MotionEvent的处理对象


     OK,结论到此结束,我们应该提出问题。
      一、既然MotionEvent事件是由dispatchTouchEvent来分发的,那么他和onInterceptTouchEvent又是什么关系呢

        二、onInterceptTouchEvent和onTouchEvent 是怎样来完成事件分发的

    那么,到了现在,我们的主题只有一个,解决上面的两个问题即可。
     对于第一个问题,最好的解决方式,很明显我们需要靠源码来解决
     下面,我先给出ViewGroup重写之后的dispatchTouchEvent函数,这里我们需要注意的事他并没有调用super.dispatchTouchEvent。而是实实在在的重写了所有逻辑(至于View源码的dispatchTouchEvent,各位看官去我的上一篇博文里面去看看吧
@Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
        }

        if (DBG_MOTION || DBG_TOUCH) {
            Xlog.d(TAG, "(ViewGroup)dispatchTouchEvent 1: ev = " + ev + ",mFirstTouchTarget = "
                    + mFirstTouchTarget + ",this = " + this);
        }

        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);//这里开始判断
                    /// M : add log to help debugging
                    if (intercepted == true) {
                        if (DBG_TOUCH) {
                            Xlog.d(TAG, "Touch event was intercepted event = " + ev + ",this = " + this);
                        }
                    }
                    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;
            if (DBG_MOTION) {
                Xlog.d(TAG, "(ViewGroup)dispatchTouchEvent 2: actionMasked = " + actionMasked
                        + ",intercepted = " + intercepted + ",canceled = " + canceled + ",split = "
                        + split + ",mChildrenCount = " + mChildrenCount + ",mFirstTouchTarget = "
                        + mFirstTouchTarget + ",this = " + this);
            }

            TouchTarget newTouchTarget = null;
            boolean alreadyDispatchedToNewTouchTarget = false;
if (!canceled && !intercepted) {     //依据interceptd 分析转折点
                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 View[] children = mChildren;

                        final boolean customOrder = isChildrenDrawingOrderEnabled();
                        for (int i = childrenCount - 1; i >= 0; i--) {
                            final int childIndex = customOrder ?
                                    getChildDrawingOrder(childrenCount, i) : i;
                            final View child = children[childIndex];
                            if (!canViewReceivePointerEvents(child)
                                    || !isTransformedTouchPointInView(x, y, child, null)) {
                                if (DBG_MOTION) {
                                    Xlog.d(TAG, "(ViewGroup)dispatchTouchEvent continue 6: i = "
                                            + i + ",count = " + childrenCount + ",child = " + child
                                            + ",this = " + this);
                                }
                                continue;
                            }

                            newTouchTarget = getTouchTarget(child);
                            if (DBG_MOTION) {
                                Xlog.d(TAG, "(ViewGroup)dispatchTouchEvent to child 3: child = "
                                        + child + ",childrenCount = " + childrenCount + ",i = " + i
                                        + ",newTouchTarget = " + newTouchTarget + ",idBitsToAssign = " 
                                        + idBitsToAssign + ",mFirstTouchTarget = " + mFirstTouchTarget 
                                        + ",this = " + this);
                            }
                            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 = childIndex;
                                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) {
                if (DBG_MOTION) {
                    Xlog.d(TAG, "(ViewGroup)dispatchTouchEvent mFirstTouchTarget = null, canceled = "
                            + canceled + ",this = " + this);
                }
                // 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 (DBG_MOTION) {
                            Xlog.d(TAG, "dispatchTouchEvent middle 5: cancelChild = " + cancelChild
                                    + ",mFirstTouchTarget = " + mFirstTouchTarget + ",target = "
                                    + target + ",predecessor = " + predecessor + ",next = " + next
                                    + ",this = " + this);
                        }
                        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 (DBG_MOTION) {
            Xlog.d(TAG, "(ViewGroup)dispatchTouchEvent end 4: handled = " + handled + ",mFirstTouchTarget = "
                    + mFirstTouchTarget + ",this = " + this);
        }

        if (!handled && mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onUnhandledEvent(ev, 1);
        }
        return handled;
    }

    
      通过上面我标红色的代码(做标记地方,显示有问题),我们很明显的看得出来通过onInterceptTouchEvent最终交给了dispatchTransformedTouchEvent来处理,那么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 (DBG_MOTION) {
            Xlog.d(TAG, "dispatchTransformedTouchEvent 1: event = " + event + ",cancel = "
                    + cancel + ",oldAction = " + oldAction + ",desiredPointerIdBits = "
                    + desiredPointerIdBits + ",mFirstTouchTarget = " + mFirstTouchTarget
                    + ",child = " + child + ",this = " + this);
        }

        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);
            if (DBG_MOTION) {
                Xlog.d(TAG, "Dispatch cancel action end: handled = " + handled + ",oldAction = "
                        + oldAction + ",child = " + child + ",this = " + this);
            }
            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) {
            Xlog.i(TAG, "Dispatch transformed touch event without pointers in " + this);
            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);
                }
                if (DBG_MOTION) {
                    Xlog.d(TAG, "dispatchTransformedTouchEvent 2 to child " + child
                            + ",handled = " + handled + ",mScrollX = " + mScrollX + ",mScrollY = "
                            + mScrollY + ",mFirstTouchTarget = " + mFirstTouchTarget + ",event = "
                            + event + ",this = " + this);
                }
                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);
        }

        if (DBG_MOTION) {
            Xlog.d(TAG, "dispatchTransformedTouchEvent 3 to child " + child + ",handled = "
                    + handled + ",mScrollX = " + mScrollX + ",mScrollY = " + mScrollY
                    + ",mFirstTouchTarget = " + mFirstTouchTarget + ",transformedEvent = "
                    + transformedEvent + ",this = " + this);
        }

        // Done.
        transformedEvent.recycle();
        return handled;
    }

        从上面的代码来判断我们假设我们不重载
public boolean onInterceptTouchEvent(MotionEvent ev) {
        return false;
    }

那么很明显了,我们的ViewGroup不会吃掉本次MotionEvent
从上一博文中的MyImageView被点击来判断
当我们点击我们ImageView时
技术分享

我们继续接着我们的Log来分析
MotionEvent事件首先传递给了我们的MyFrameLayout,这时,我们要注意虽然我们设置了onTouchListener和OnClickListener,但是因为我们没有重载onInterceptTouchEvent默认的onInterceptTouchEvent直接return false;所以我们的MyFrameLayout没有资格消费本次的MotionEvent事件,最终经过判断dispatchTransformedTouchEvent把事件交给了我们的MyImageView
handled = child.dispatchTouchEvent(transformedEvent);
当然 因为我们的MyImageView 也设置了onTouchListener和onClickListener,所以他顺理成章的消费了本次MotionEvent

当我们再点击我们FrameLayout
技术分享
这时虽然我们的onInterceptTouchEvent还是return  false;但是我们的touchTarget是空的,所以
if (child == null) {
            handled = super.dispatchTouchEvent(transformedEvent);
        } else 
我们的MyFrameLayout 也还是最终享受到了MotionEvent
  所以说  不一定我们的onInterceptTouchEvent 返回了false 我们的ViewGroup就不能接收到OnTouchEvent了


这里,我们再次考虑  当我们的onInterceptTouchEvent 被我们重载  并返回了true 那么走的路线就不一样了
if (!canceled && !intercepted) {     //依据interceptd 分析转折点</span>
if (mFirstTouchTarget == null) {
                if (DBG_MOTION) {
                    Xlog.d(TAG, "(ViewGroup)dispatchTouchEvent mFirstTouchTarget = null, canceled = "
                            + canceled + ",this = " + this);
                }
                // No touch targets so treat this as an ordinary view.
                handled = dispatchTransformedTouchEvent(ev, canceled, null,
                        TouchTarget.ALL_POINTER_IDS);


这里注意,因为我们的onInterceptTouchEvent return true;我们直接跳过了Child的判断并最终导致我们的child == null;那么很明星我们的MotionEvent只能被我们的ViewGroup消费了。
        那么,到了这里我们开始大胆的做出假设性结论:
        一、只要我们的onInterceptTouchEvent return true 那么我们的MotionEvent 与ChildView 无缘
         二、如果我们的onInterceptTouchEvent  return false;那么我们的ChildView  会优先获得MotionEvent ,但是当我们的ChildView  并不在TouchTarget上,我们的ViewGroup依然有机会得到本次MotionEvent 。
     那么接下来,我们所有做的就只能验证我们的结论了。
    这里我们先验证第一条// 这里的验证我们将依据ACTION的不同来分析。
    这里我们对我们的MyFrameLayout  做出改变(重载onInterceptTouchEvent 
@Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        switch(event.getAction()){
        case MotionEvent.ACTION_DOWN:{
            Log.d(TAG,"MyFrameLayout onInterceptTouchEvent ACTION_DOWN return true");
            return true;
        }
        case MotionEvent.ACTION_MOVE:{
            Log.d(TAG,"MyFrameLayout onInterceptTouchEvent ACTION_MOVE return true");
            return true;
        }
        case MotionEvent.ACTION_UP:{
            Log.d(TAG,"MyFrameLayout onInterceptTouchEvent ACTION_UP return true");
            return true;
        }
        }
        return true;
    }

简而言之,就是不论什么情况下,我们都要我们的onInterceptTouchEvent  return true;
并分别改写我们的FrameLayout 和ImageView的OnTouchEvent函数
 @Override
    public boolean onTouchEvent(MotionEvent event) {
        Log.d(TAG,"MyFrameLayout onTouchEvent"+event.getAction());
        switch(event.getAction()){
        case MotionEvent.ACTION_DOWN:{
            Log.d(TAG,"MyFrameLayout onTouchEvent ACTION_DOWN return true");
            break;
        }
        case MotionEvent.ACTION_MOVE:{
            Log.d(TAG,"MyFrameLayout onTouchEvent ACTION_MOVE return true");
            break;
        }
        case MotionEvent.ACTION_UP:{
            Log.d(TAG,"MyFrameLayout onTouchEvent ACTION_UP return true");
            break;
        }
        }
        return super.onTouchEvent(event);
    }

 @Override
    public boolean onTouchEvent(MotionEvent event) {
        Log.d(TAG,"MyImageView onTouchEvent"+event.getAction());
        switch(event.getAction()){
        case MotionEvent.ACTION_DOWN:{
            Log.d(TAG,"MyImageView onTouchEvent ACTION_DOWN return true");
            break;
        }
        case MotionEvent.ACTION_MOVE:{
            Log.d(TAG,"MyImageView onTouchEvent ACTION_MOVE return true");
            break;
        }
        case MotionEvent.ACTION_UP:{
            Log.d(TAG,"MyImageView onTouchEvent ACTION_UP return true");
            break;
        }
        }
        return super.onTouchEvent(event);
    }

   首先我们点击我们的MyImageView,我们来看一下Log
技术分享

很明显,一旦我们的onInterceptTouchEvent  return true,我们的子View就与MotionEvent 无缘了

接下来,我们继续点击我们的FrameLayout
Log 图,我就不贴了,和上面一模一样,为什么呢,很显然我们的子View就与MotionEvent 无缘了

接下来,我们继续做出改变
我们在FrameLayout中将onInterceptTouchEvent  中的MotionEvent.ACTION_DOWN returnfalse;
依然点击我们的点击我们的MyImageView
技术分享

这里我们来分析一下Log   首先我们需要知道3 == MotionEvent.ACTION_CANCEL
那么,首先因为我们的onInterceptTouchEvent  在MotionEvent.ACTION_DOWN returnfalse;所以我们的FrameLayout没办法继续往下走了(不会走onTouch 和 onTouchEvent)转而MotionEvent事件转交给我们的ImageView
所以我们的ImageView总算是得到了MotionEvent.ACTION_DOWN
但是在经过MotionEvent.ACTION_MOVE时,因为我们的onInterceptTouchEvent  返回了true,所以很明显我们的FrameLayout告诉了系统 这次的MotionEvent事件我要了,所以我们的ImageView的到了MotionEvent.ACTION_CANCEL  反而我们的FrameLayout 可以继续往下走了。
所以说我们的ImageView猜中了开头缺有猜中结局,虽然得到了ACTION_DOWN,但却什么都做不了只能以ACTION_CANCEL草草收场,所以也不会触发onClickListener

同理我们的FrameLayout虽然得到了ACTION_UP 但是没有ACTION_DOWN 也是徒劳。同样不会OnClickListener

到了这里,我们同样也是可以类推的 如果我们的FrameLayout在onInterceptTouchEvent  在ACTION_MOVE中返回false,我们的ImageView可以接受到ACTION_MOVE 但是最终接受的还是ACTION_CANCEL依然接受不到ACTION_UP ,反而我们的FrameLayout 只能得到ACTION_UP ,简而言之就是说依据onInterceptTouchEvent  的返回值不同各MotionEvent事件最终要么被ViewGroup 要么被ChildView获取

从上面的Log,我们依然可以看到的是 onInterceptTouchEvent 并不会在每一次 MotionEvent事件(ACTION_DOWN、ACTION_MOVE、ACTION_UP 等)调用,例如果在ACTION_DOWN return true 交给了ViewGroup 而View没有得到的话,ACTION_MOVE时就不会调用,但是如果return false,ChildView 得到了ACTION_MOVE时就会再次调用

技术分享

版权声明:本文为博主原创文章,未经博主允许不得转载。

onInterceptTouchEvent 与 onTouchEvent 分析与MotionEvent在ViewGroup与View中的分发

标签:onintercepttoucheven   ontouchevent   motionevent的分发   

原文地址:http://blog.csdn.net/jaysong2012/article/details/46909959

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!