五、写在最后" />
当前位置: 代码迷 >> Android >> 五、写在最后
  详细解决方案

五、写在最后

热度:36   发布时间:2016-04-28 02:10:28.0
菜鸟进阶之Android Touch事件传递(三)

费了这么大劲,终于写完了,这是我的原创。转载请说明出处:http://blog.csdn.net/bingospunky/article/details/44156771

这是touch传递系列文章的第三篇,我打算在这篇文章里从源码的角度解释dispatchTouchEvent、onInterceptTouchEvent、onTouchEvent方法的返回值影响touch传递的原理。

如果想了解touch和click的那些事,请浏览touch事件传递系列的第一篇http://blog.csdn.net/bingospunky/article/details/43603397

如果想了解touch事件一步一步传递的路线,请浏览touch事件传递系列的第二篇http://blog.csdn.net/bingospunky/article/details/43735497

我们知道view的继承关系,这篇文章中只介绍view和viewgroup组件中上述三个方法的实现。

一、onInterceptTouchEvent

代码A:

public boolean onInterceptTouchEvent(MotionEvent ev) {        return false;}
这是viewgroup的onInterceptTouchEvent方法。我们知道viewgroup得到touch事件后,有两个选择,自己处理还是分给childview处理。由该方法的返回值决定,返回true代表自己处理。

二、dispatchTouchEvent

代码B(boolean android.view.View.dispatchTouchEvent(MotionEvent event):

/**     * 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) {        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)) {            //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;    }

代码C(boolean android.view.ViewGroup.dispatchTouchEvent(MotionEvent ev)):


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 (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 = buildOrderedChildList();                        final boolean customOrder = preorderedList == null                                && isChildrenDrawingOrderEnabled();                        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);                            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();                                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;                            }                        }                        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;    }

代码D(void android.view.ViewGroup.cancelAndClearTouchTargets(MotionEvent event)):

private void cancelAndClearTouchTargets(MotionEvent event) {        if (mFirstTouchTarget != null) {            boolean syntheticEvent = false;            if (event == null) {                final long now = SystemClock.uptimeMillis();                event = MotionEvent.obtain(now, now,                        MotionEvent.ACTION_CANCEL, 0.0f, 0.0f, 0);                event.setSource(InputDevice.SOURCE_TOUCHSCREEN);                syntheticEvent = true;            }            for (TouchTarget target = mFirstTouchTarget; target != null; target = target.next) {                resetCancelNextUpFlag(target.child);                dispatchTransformedTouchEvent(event, true, target.child, target.pointerIdBits);            }            clearTouchTargets();            if (syntheticEvent) {                event.recycle();            }        }    }

代码E(boolean android.view.ViewGroup.dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,View child, int desiredPointerIdBits)):

/**     * 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;    }
代码F(private TouchTarget  android.view.ViewGroup.addTouchTarget(View child, int pointerIdBits)):

/**     * Adds a touch target for specified child to the beginning of the list.     * Assumes the target child is not already present.     */    private TouchTarget addTouchTarget(View child, int pointerIdBits) {        TouchTarget target = TouchTarget.obtain(child, pointerIdBits);        target.next = mFirstTouchTarget;        mFirstTouchTarget = target;        return target;    }

view的dispatchTouchEvent

26行先让listener处理touch事件,如果没有被handled,那么30行再调用onTouchEvent处理touch事件。返回值注释里有True if the event was handled by the view, false otherwise.

viewgroup的dispatchTouchEvent

对于一个a new touch gesture,我们从down->move->up的顺序来看:

down事件

a(该viewgroup或者child消化touch事件)

①代码C第12--18行,清除之前的一些状态,具体代码在下面解释。②代码C第26行,onInterceptTouchEvent返回false,intercepted值为false。③代码C第42行split为true。④代码C第45行的if判断,表达式的值为true,可以执行if里面的内容。如果它的某个子view可以接受这个touch事件,那么执行代码C第77--104行的代码。代码C第77行返回null,所以78--83行的代码不被执行。⑤代码C第86行,向适当的子view分发touch事件,如果该事件被handled,那么执行if里面的内容。我们先看代码E(dispatchTransformedTouchEvent方法):代码E第25--26行,求得的两个值,MotionEvent的id的对应值,具体见以后的介绍MotionEvent的文章,我在这里解释他们相等和不相等代表什么意思就可以了。代码E第39行,返回true代表当前的touch事件只有一个点触屏,返回false,那么把这个touch事件分离出来。代码E第60--71行,如果child为空,那么使用该viewgroup父类的dispatchTouchEvent处理该touch事件,否则让child处理该touch事件。⑥代码C第87--104行,如果该touch事件被消化掉了,那么做一些设置,这里重要的是102行的addTouchTarget这个方法,见代码F,执行完这个方法后mFirstTouchTarget属性不为空了。⑦对于代码C第110--118行,我们不执行,因为当前newTouchTarget不为空。⑧在代码C第122--157行的代码中,我们执行135、154、155行一次。⑧最终返回true。

b(该viewgroup或者child不消化touch事件)

①②③④⑤同上,⑥代码C,由于第86行的方法返回false,所以第87--104行代码不执行,截止至107行,newTouchTarget和mFirstTouchTarget都为空。⑦代码C第110--118行不执行。⑧代码C第125--126行代码被执行,第二个参数为false,由于第三个参数为null,那么这个方法里的操作为调用viewgroup的父类的方法,自己处理touch事件。

move事件

分情况讨论,根据mFirstTouchTarget是否为空。(mFirstTouchTarget为空代表down事件没有被代码C第86行的方法消化掉)

a(mFirstTouchTarget为空)

①执行代码C第34行,intercepted = true;。②代码C第46--119行代码不执行。③执行代码C第125--126行,第二个参数我猜测应该是false(对于这个参数,我往下追了一下,在View里虽然只有两个方法改变它,但由于我阅读的源码量不够,还不能给它确定值。但是从字面意思以及它的效果上猜测应该是false),第三个参数为空的情况下,125--126行的代码就是让该viewgroup的父类去消化这个touch事件。

b(mFirstTouchTarget不为空)

①由于该事件是move事件,所以代码C第4--118行代码不会被执行。②由于mFirstTouchTarget不为空,执行代码C第128--156行代码。由于newTouchTarget为空,mFirstTouchTarget不为空,那么会执行代码C第137--152行代码。根据代码C第139行dispatchTransformedTouchEvent方法的返回值,在第141行设置handled的值。关于代码C第143--152行,想做的是根据cancelChild这个属性,把需要去掉的TouchTarget在链中去掉(关于怎么去掉的,这就是个数据结构中去掉链表中一节的操作,开始让predecessor=target,通过cancelChild控制continue,以至于target = target.next,下面再操作predecessor.next = target.next.next。代码并不是这么直接,如果你把相同的量替换一下就可以看到是这么完成的),当然这个在链表中去掉一节,不是我现在的重点,因为现在是在介绍down事件后的第一个move事件的执行过程,按照我的理解,在这里不会执行代码C第143--152行的代码。

up事件

up事件,不轮mFirstTouchTarget是否为空,都同move一样处理,因为处理move事件并没有改变那些状态的量的值。

up事件相对于move事件额外的处理是:代码C第163行,设置一些状态为空。

cancel事件

cancel事件也是一个比较重要的事件,但是这个事件不能由我们主动点击屏幕生成,所以在这里就不详细介绍了,你可以按照上面的方式护住心脉,自行运功疗伤(额,这好像是一灯大师对杨过说的话,小笼包电视看多了)。

三、onTouchEvent

这个方法是android.view.View里的方法,就是让该view处理touch事件。它是处理这个touch,和传递无关。有关这个方法详细点的解释,可以参考我的这个系列文章中的第一篇。

四、more

不知道你有没有看到这里,我觉得看到这里对事件传递,尤其是dispatchTouchEvent有了更深的体会,通过源码我们就能解释更多的事情。比如:①一个down事件传递给一个viewgroup的child,如果该child不消化这个,那么这个down事假的后续事件就不会再传递给这个child。因为由于child没消化down事件,那么viewgroup的mFirstTouchTarget为空,那么会执行代码C第125--126行代码,直接把后续事件交给viewgroup的父类进行处理。②一个down事件到达viewgroup,会调用该viewgroup的onInterceptTouchEvent函数,之后传递给对应的child,如果child没有消化down,而该viewgroup调用父类的方法,自己消化掉了down事件。那么这个down事件的后续事件不会在通过onInterceptTouchEvent函数,那这是怎么实现的呢?对于这一点,网上由一个解释:onInterceptTouchEvent是截断的意思,因为child没有消化down,那么后续事件不会传递给child,那么也就没有截断的必要。这个解释相当合理,但是这只是肤浅的解释,只是这样,我们还是不能领会到写android系统的那些老头(应该是老头吧,哈哈)的深奥之处。从源码的角度怎么解释呢?child没有消化down,那么mFirstTouchTarget为空,那么代码C第22--23行的代码里if条件不成立,所以26行的onInterceptTouchEvent方法不会被调用。

四、声明

1.我介绍的内容并不是完全的,我只介绍了down、move、up事件的传递处理过程,只考虑了一个触点的情况,把一些情况简化了,因为源码里这块内容确实是挺多。比如代码C第86行方法传递的child参数我默认不会是空,我不考虑不是空的情况,那么什么时候是空呢,可能是view.gone的时候。

2.由mFirstTouchTarget为首的链表,对应着这个viewgroup的child消化的多个触点事件的信息。怎么理解呢?就是该链表里每个TouchTarget代表一个被该viewgroup的child消化的触点touch,TouchTarget里面包含触点的child view是哪个,touch的id。

3.对于这部分内容,虽然代码量并不是很多,但却是关系错综复杂。对于同样是菜鸟的你,我建议,在学习这部分代码的时候一定要进行控制变量,还有要注意关键的变量的值是怎么变化的以及变化之后的值。

4.文章里我忽略掉了关于MotionEvent的多触点的部分,其实这一部分也挺有意思的。我也在刚刚学习MotionEvent这个累,后面的文章中要是有机会,我也写写MotionEvent它。

五、写在最后

昨天元宵节刚刚过去,现在看月亮都要交16块钱的赏月费了(全国统一价:十五的月亮16元)。文章看到这里的你还不赶快评论啊。评论啊。评论啊。评论啊。评论啊。


  相关解决方案