Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android點擊事件的分發過程

android點擊事件的分發過程

編輯:關於Android編程

本文將講述android點擊事件的分發過程

我的上一篇文章講述了android點擊事件的來源,本文接著講述當點擊事件傳輸到Activity之後 分發的過程是什麼樣的。通過上一篇文章我們知道,事件最終會通過activity分發到PhoneWindow再到DecorView最後到他的子View。

那我們就從Activity的dispatchTouchEvent方法看起吧。
Activity#dispatchTouchEvent

 public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            onUserInteraction();
        }
        //調用 phoneWindow的 superDiapatchTouchEvent
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        // 如果phoneWindow#superDiapatchTouchEvent為false ,
      //  則會調用Activity的 onTouchEvent
        return onTouchEvent(ev);
    }

從這段代碼可以看出:activity把事件交給了 phoneWindow,向下傳遞。
如果下層沒有處理這個事件,那麼activity將調用自己的onTouchEvent來處理這個事件。

我們接看PhoneWindow的superDispatchTouchEvent
PhoneWindow#superDispatchTouchEvent

@Override
    public boolean superDispatchTouchEvent(MotionEvent event) {
        //傳遞給DecorView
        return mDecor.superDispatchTouchEvent(event);
    }

它將事件傳遞給了DecorView。
DecorView的superDispatchTouchEvent

public boolean superDispatchTouchEvent(MotionEvent event) {
            return super.dispatchTouchEvent(event);
        }

它這裡調用了super.dispatchTouchEvent(event),實際就是調用了ViewGoup的
dispatchTouchEvent方法。
ViewGroup#dispatchTouchEvent

 @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
       ...

            if (actionMasked == MotionEvent.ACTION_DOWN) {
         cancelAndClearTouchTargets(ev);
                // 1、清除 了disallowIntercept  標記
                resetTouchState();
            }

            // Check for interception.
            final boolean intercepted;
         // 2 、判斷是否攔截,這個if語句actionMasked == MotionEvent.ACTION_DOWN|| mFirstTouchTarget != null
         // 在ACTION_DOWN 或者 mFirstTouchTarget!=null的時候進入
         // 通過下文分析會得出:如果不攔截事件,將事件交由子View處理的
//mFirstTouchTarget 不會被賦值,也就是mFirstTouchTarget!=null 不成立。
//那麼就會有一條結論:當ViewGroup攔截事件後,那麼在這個事件序列中,
//將不會進入onInterceptTouchEvent(ev)判斷,而是直接交由ViewGroup自身處理。
        //原因是如果攔截了,下個事件不可能是ACTION_DOWN,並且mFirstTouchTarget==null ,所以上述結論成立!

            if (actionMasked == MotionEvent.ACTION_DOWN
                    || mFirstTouchTarget != null) {
                final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
                //3、這個標示可以通過requestDisallowInterceptTouchEvent
                //進行設置,這個標志將影響事件的攔截,即如果這個設了這個標志,
                //ViewGroup將不攔截事件,但這個對ACTION_DOWN無效,
                //原因在於ACTION_DOWN時 會清楚標志,看1號注釋
                if (!disallowIntercept) {
                    intercepted = onInterceptTouchEvent(ev);
                    ev.setAction(action); // restore action in case it was changed
                } else {
                    intercepted = false;
                }
            } else {

                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;

            // 4、如果不攔截將事件往下傳遞
            if (!canceled && !intercepted) {

                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 preorderedList = buildOrderedChildList();
                        final boolean customOrder = preorderedList == null
                                && isChildrenDrawingOrderEnabled();
                        final View[] children = mChildren;
                        // 5、遍歷子View
                        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 (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);
                            // 6、這個方法將事件分發給子View (即調用子View的 disatchTouchEvent犯法)
                            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();
                                // 7、對mFirstTouchEvent進行賦值
                                newTouchTarget = addTouchTarget(child, idBitsToAssign);
                                alreadyDispatchedToNewTouchTarget = true;
                                break;
                            }


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

            //8、如果父控件沒有子View 或者子View的 disPatchTouchEvent返回fasle ,
            //即沒有子View處理事件的話,將會走這個if分支
            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 {
                    // 9、如果子View正在處理事件,而此時ViewGroup的onIntercepted返回true,
                    //此時ViewGroup就會偷取事件。
                    //這個分支會回收target,將重新使得mFirstTouchEvent為null,
                    //並且子View會受到一個Cancel事件
                        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;
    }

這個方法代碼比較長,內容也比較多。我們先看第一個注釋的代碼:

  private void resetTouchState() {
        clearTouchTargets();
        resetCancelNextUpFlag(this);
        //清楚標志位
        mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;
        mNestedScrollAxes = SCROLL_AXIS_NONE;
    }

看以看到如果是ACTION_DOWN事件的話,它會清楚FLAG_DISALLOW_INTERCEPT這個標志

接著看第二個注釋的地方:

  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 {

                intercepted = true;
            }

這塊代碼,注釋中已經說得差不多了。2條結論:
1、如果ViewGroup決定攔截事件,那麼將不會再進入這個分支判斷,後續的事件將都交由它處理。
2、可以使用 requestDisallowInterceptTouchEvent,使得ViewGroup不攔截事件,但為ACTION_DOWN事件無效。

接著會遍歷所有的子View 並調用dispatchTransformedTouchEvent進行事件分發,我們來看這個方法的代碼:

private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
            View child, int desiredPointerIdBits) {
        final boolean handled;

         // 處理cancle 事件
        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());
            }
        //傳遞給子View
            handled = child.dispatchTouchEvent(transformedEvent);
        }

        // Done.
        transformedEvent.recycle();
        //返回結果
        return handled;
    }

這個方法,將會進行事件分發,如果傳入的child不為null,則會傳遞給子View,調用子View的dispatchTouchEvent。

如果child為null 則會掉用 super.dispatchTouchEvent。當然ViewGroup的 父類是View 所以會執行view 的dispatchTouchEvent,這時就會調用ViewGroup的onTouchEvent了。

View#dispatchTouchEvent

 public boolean dispatchTouchEvent(MotionEvent event) {
        // If the event should be handled by accessibility focus first.
        if (event.isTargetAccessibilityFocus()) {
            // We don't have focus or no virtual descendant has it, do not handle the event.
            if (!isAccessibilityFocusedViewOrHost()) {
                return false;
            }
            // We have focus and got the event, then use normal event dispatch.
            event.setTargetAccessibilityFocus(false);
        }
    //處理結果
        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;
            //如果 mOnTouchListener.onTouch()返回 true,則不會調用
            //onTouchEvent,這裡mOnTouchListener的優先級比較高
            if (li != null && li.mOnTouchListener != null
                    && (mViewFlags & ENABLED_MASK) == ENABLED
                    && li.mOnTouchListener.onTouch(this, event)) {
                result = true;
            }
        // 執行 onTouchEvent
            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;
    }

這樣事件就分發到子View的onTouchEvent或者 自身的onTouchEvent了。

我們回過頭,在看一下ViewGroup#dispatchTouchEvent這個方法中,注釋7~9,看看它是怎麼傳遞事件到自身 onTouchEvent的,和如果給mFirstTouchEvent賦值的。

我們先來看注釋7、addTouchTarget方法是怎麼賦值的。

   private TouchTarget addTouchTarget(View child, int pointerIdBits) {
        TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
        target.next = mFirstTouchTarget;
        mFirstTouchTarget = target;
        return target;
    }

在看第8條注釋,如果mFirstTouchEvent==null 說明沒有子View處理事件,這時將向上冒泡,那我們來看看它怎麼處理的。

 // Dispatch to touch targets.
            if (mFirstTouchTarget == null) {
                // No touch targets so treat this as an ordinary view.
                //調用這個方法,傳入的child ==null
                handled = dispatchTransformedTouchEvent(ev, canceled, null,
                        TouchTarget.ALL_POINTER_IDS);

這是將調用dispatchTransformedTouchEvent 並傳入的child==null,那麼將會執行
dispatchTransformedTouchEvent 方法中的
handled = super.dispatchTouchEvent(event);
這個上文已經分析過了。

 if (child == null) {
                handled = super.dispatchTouchEvent(event);
            } else {
                handled = child.dispatchTouchEvent(event);
            }

在看第 9條注釋:
這個是發生在,子View可能正在處理事件(mFirstTouchEvent!=null),此時ViewGroup決定攔截事件,這是ViewGroup就會偷取子View的事件,向子View發送一個cancel事件,然後將子View從TouchTarget中移除,將導致mFirstTouchEvent重新為 null, 使得接下來的事件交由 ViewGroup自身處理
相關代碼:

 final boolean cancelChild = resetCancelNextUpFlag(target.child)
                                || intercepted;
                                //傳遞一個 cancel事件給 子View
                        if (dispatchTransformedTouchEvent(ev, cancelChild,
                                target.child, target.pointerIdBits)) {
                            handled = true;
                        }
                        if (cancelChild) {
                            if (predecessor == null) {
                                mFirstTouchTarget = next;
                            } else {
                                predecessor.next = next;
                            }
                            //回收target
                            target.recycle();
                            target = next;
                            continue;

那麼事件的分發到這裡,就基本講完了,其中很多細節目前還不是很懂,需要以後繼續學習,下面我上傳流程圖:
這裡寫圖片描述

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved