觸摸事件分發機制的實例分析(一)

我們知道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的事件,那麼後續所有事件都無法傳遞到子佈局裏面去,所以內部攔截就無法起作用了。

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