触摸事件分发机制的实例分析(一)

我们知道android中的事件分发有三个重要方法 

onIntercept

ondispatchtouchevent

ontouchevent

 他们之间的关系可以用下面的伪代码来阐述:

public boolean dispatchTouchEvent(MotionEvent e){
    boolean consume = false;
    if(onInterceptTouchEvent(ev)) {
        consume = onToucheEvent(ev);
    }else{
        consume = child.dispatchTouchEvent(ev);
    }
    return consume;
}

可以这样理解,当ViewGroup的onInterceptTouchEvent返回true,就表示要拦截这个事件,接着事件交由ViewGroup

处理,即它的OnTouchEvent方法会被调用;如果这个ViewGroup的onInterceptTouchEvent返回false就表示它不拦截这个事件,这时当前事件就传递给它的子元素来处理,接着子元素的dispatchTouchEvent就会被调用。如此往复直到事件被最终处理。

ontouch和onclick之间 的关系 ?

当一个View需要处理事件时,如果设置了OnTouchListener,那么OnTouchListener中的OnTouch就会被调用。这时,如果OnTouch如果返回false,当前View的onTouchEvent就会被调用;如果返回true,那么OnTouchEvent就不会被调用。只有OnTouch被调用后,我们通常设置的OnClick方法才会被调用。

事件滑动冲突例子

事件分发在应用层面的应用只是滑动冲突的解决。

这里用viewpager嵌套listview的例子来讲解。

其实用viewpager来讲事件滑动冲突并不是特别好,因为viewpager在内部已经帮我们解决了滑动冲突。

如果这个viewpager在实际操作可以是具体的一个自定LinearLayout或者其他什么的,原理是一样的。

我们为了掩饰滑动冲突的解决思路,在viewpager里面嵌套listview,并且在viewpager的onInterceptTouchEvent方法里面返回true,表示viewpager父布局拦截了事件,这时候里面的listview就不能上下滑动了。如果在viewpager的onInterceptTouchEvent方法里面返回false,表示viewpager不拦截事件,那么这时候viewpager又不能左右滑动了,这就是滑动冲突。

为什么会这个样子?

这就需要分析ViewGroup的dispatchTouchEvent源码。(点击事件分发会先执行Activity的dispatchTouchEvent,然后执行到ViewGrou的dispatchTouchEvent方法)

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

这个方法的代码很长,但是不用每个细节都关注。主要的作用是完成事件的分发。

当ACTION_DOWN事件的时候,代码里会执行cancelAndClearTouchTargets和resetTouchState方法。其中,resetTouchState用来重置一些状态。

intercepted以及cenceled都是为false的时候,也就是说,既不取消事件,也不拦截事件的时候,就开始倒序遍历子View。

对于子ViewGroup的子view根据Z轴座标进行排序,分别将ACTION_DOWN以及后续事件交由他们去处理。所以最外面的View会最先收到事件,这也就是我们平时记的,ACTION_DOWN等触摸事件是先由最外面的View一层层向根ViewGroup传递的道理是一样的。

调用dispatchTransformedTouchEvent方法里面调用childview的dispatchTouchEvent()方法,从而完成事件由ViewGroup到View的一个分发。

那么,滑动冲突如何去解决?

1.外部拦截法 

外部拦截的思路比内部拦截要简单,父容器针对不同的事件选择是否进行拦截。

     public boolean onInterceptTouchEvent (MotionEvent event){
            boolean intercepted = false;
            int x = (int) event.getX();
            int y = (int) event.getY();
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    intercepted = false;//必须不能拦截,否则后续的ACTION_MOME和ACTION_UP事件都会拦截。
                    break;
                case MotionEvent.ACTION_MOVE:
                    if (父容器需要当前点击事件) {
                        intercepted = true;
                    } else {
                        intercepted = false;
                    }
                    break;
                case MotionEvent.ACTION_UP:
                    intercepted = false;
                    break;
                default:
                    break;
            }
            mLastXIntercept = x;
            mLastXIntercept = y;
            return intercepted;
        } 

2.内部拦截法

内部拦截的话可以直接看我这个例子demo了

具体就是看这个demo

Github地址

它主要的逻辑就是重写内部类的dispatchTouchEvent方法。

  @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        int x = (int) ev.getX();
        int y = (int) ev.getY();
        switch (ev.getAction()){
            case MotionEvent.ACTION_DOWN: {
                getParent().requestDisallowInterceptTouchEvent(true);
                break;
            }
                case MotionEvent.ACTION_MOVE:{
                    int deltax = x - mLastX;
                    int deltay = y - mLastY;
                    if(Math.abs(deltax) > Math.abs(deltay) ){
                        getParent().requestDisallowInterceptTouchEvent(false);
                    }
                    break;

                }

            case MotionEvent.ACTION_UP:
                break;

        }

        return super.dispatchTouchEvent(ev);
    }

这里有个难点,就是仅仅这样做还是不够的,就是说还要在父布局里面的onInterceptTouchEvent里面增加一个处理,就是不拦截ACTION_DOWN事件,为什么不能拦截这个事件呢,因为这个事件比较特殊,不受FLAG_DISALLOW_INTERCEPT这个标志位的控制,所以一旦父容器拦截了ACTION_DOWN的事件,那么后续所有事件都无法传递到子布局里面去,所以内部拦截就无法起作用了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章