android開發筆記 (二)View的事件分發機制

1. 基礎認知

 

 

1.1 屏幕的直角座標系

 

1.2 事件分發的對象是誰?

Touch事件:當用戶觸摸屏幕時(View 或 ViewGroup派生的控件),將產生Touch事件

Touch事件的相關細節(發生觸摸的位置、時間等)被封裝成MotionEvent對象

 

1.3 Touch事件的分類

  • MotionEvent.ACTION_DOWN  //按下View(所有事件的開始)

  • MotionEvent.ACTION_UP  //擡起View(與DOWN對應)

  • MotionEvent.ACTION_MOVE  //滑動View

  • MotionEvent.ACTION_CANCEL  //結束事件(非人爲原因)

 

1.4 事件分發的本質

將點擊事件(MotionEvent)傳遞到某個具體的View 且 處理的整個過程

 

1.5 事件分發的順序

Activity -> ViewGroup -> View

 

1.6 事件分發過程主要的協作方法

dispatchTouchEvent() 、onInterceptTouchEvent()和onTouchEvent()

方法 作用 調用時機
dispatchTouchEvent() 分發touch事件 當touch事件能夠傳遞到當前單位(Activity,Viewgroup,View)時,該方法就會調用
onInterceptTouchEvent() 判斷是否攔截了某個事件,只存在於ViewGroup,普通的View沒有此方法 在ViewGroup的dispatchTouchEvent()內部調用
onTouchEvent() 處理touch事件 在dispatchTouchEvent()內部調用

 

 

2. 事件機制源碼分析

2.1 Activity的事件分發機制

當一個點擊事件發生時,事件最先傳到`Activity`的`dispatchTouchEvent()`進行事件分發

2.1.1 activity內事件機制源碼分析

/**
     * Called to process touch screen events.  You can override this to
     * intercept all touch screen events before they are dispatched to the
     * window.  Be sure to call this implementation for touch screen events
     * that should be handled normally.
     *
     * @param ev The touch screen event.
     *
     * @return boolean Return true if this event was consumed.
     */
    public boolean dispatchTouchEvent(MotionEvent ev) {
        // 一般事件列開始都是DOWN事件 = 按下事件,故此處基本是true
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            //分析1
            onUserInteraction();
        }
        //分析2
        if (getWindow().superDispatchTouchEvent(ev)) {
            // 若getWindow().superDispatchTouchEvent(ev)的返回true
                // 則Activity.dispatchTouchEvent()就返回true,則方法結束。即 :該點擊事件停止往下傳遞 & 事件傳遞過程結束
                // 否則:繼續往下調用Activity.onTouchEvent

            return true;
        }
        //分析4
        return onTouchEvent(ev);
    }

/**
  * 分析1:onUserInteraction()
  * 作用:實現屏保功能
  * 注:
  *    a. 該方法爲空方法
  *    b. 當此activity在棧頂時,觸屏點擊按home,back,menu鍵等都會觸發此方法
  */
      public void onUserInteraction() { 

      }

/**
  * 分析2:getWindow().superDispatchTouchEvent(ev)
  *
  *     getWindow() = 獲取Window類的對象
  *     Window類是抽象類,其唯一實現類 = PhoneWindow類;即此處的Window類對象 = PhoneWindow類對象
  *     Window類的superDispatchTouchEvent()是1個抽象方法,由子類PhoneWindow類實現
  */
    @Override
    public boolean superDispatchTouchEvent(MotionEvent event) {
        // mDecor = 頂層View(DecorView)的實例對象
        // ->> 分析3
        return mDecor.superDispatchTouchEvent(event);
    }

/**
  * 分析3:mDecor.superDispatchTouchEvent(event)
  * 屬於頂層View(DecorView),也就是一個界面中最外層的那個layout
  * 
  *     DecorView類是PhoneWindow類的一個內部類
  *     DecorView繼承自FrameLayout,是所有界面的父類
  *     FrameLayout是ViewGroup的子類,故DecorView的間接父類 = ViewGroup
  */
    public boolean superDispatchTouchEvent(MotionEvent event) {
        // 調用父類的方法 = ViewGroup的dispatchTouchEvent()
        // 即 將事件傳遞到ViewGroup去處理,詳細請看ViewGroup的事件分發機制
        return super.dispatchTouchEvent(event);
    }

/**
  * 分析4:Activity.onTouchEvent()
  */
  public boolean onTouchEvent(MotionEvent event) {

        // 當一個點擊事件未被Activity下任何一個View消費時
        // 應用場景:處理髮生在Window邊界外的觸摸事件
        // ->> 分析5
        if (mWindow.shouldCloseOnTouch(this, event)) {
            finish();
            return true;
        }

        return false;
        // 即 只有在點擊事件在Window邊界外才會返回true,一般情況都返回false,分析完畢
    }

/**
  * 分析5:mWindow.shouldCloseOnTouch(this, event)
  */
    public boolean shouldCloseOnTouch(Context context, MotionEvent event) {
    // 主要是對於處理邊界外點擊事件的判斷:是否是DOWN事件,event的座標是否在邊界內等
    if (mCloseOnTouchOutside && event.getAction() == MotionEvent.ACTION_DOWN
            && isOutOfBounds(context, event) && peekDecorView() != null) {
        return true;
    }
    return false;
    // 返回true:說明事件在邊界外,即 消費事件
    // 返回false:未消費(默認)
}

2.1.2 Activity中的事件分發流程圖

 

2.2 ViewGroup事件的分發機制

2.1.1 ViewGroup源碼分析

@Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        // mInputEventConsistencyVerifier是調試用的,不會理會
        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;
        // 第1步,是否分發該事件
        // onFilterTouchEventForSecurity()表示是否要分發該觸摸事件。 
        // 如果該View不是位於頂部,並且有設置屬性使該View不在頂部時不響應觸摸事件,則不分發該觸摸事件,即返回false。
        // 否則,則對觸摸事件進行分發,即返回true。
        if (onFilterTouchEventForSecurity(ev)) {
            final int action = ev.getAction();
            final int actionMasked = action & MotionEvent.ACTION_MASK;

            // Handle an initial down.
            // 第2步,檢測是否需要清空目標和狀態
            // 如果是ACTION_DOWN(即按下事件),則清空之前的觸摸事件處理目標和狀態。
            // 這裏的情況狀態包括:
            // (01) 清空mFirstTouchTarget鏈表,並設置mFirstTouchTarget爲null。
            //      mFirstTouchTarget是"接受觸摸事件的View"所組成的單鏈表
            // (02) 清空mGroupFlags的FLAG_DISALLOW_INTERCEPT標記
            //      如果設置了FLAG_DISALLOW_INTERCEPT,則不允許ViewGroup對觸摸事件進行攔截。
            // (03) 清空mPrivateFlags的PFLAG_CANCEL_NEXT_UP_EVEN標記
            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;
            //第3步,檢查當前ViewGroup是否想要攔截觸摸事件
            //在這裏通過action是否是down事件和mFirstTouchTarget != null來判斷是否進行事件攔截
            //mFirstTouchTarget表示處理事件的child。
            //如果mFirstTouchTarget != null,表示有child正在處理事件,
            //mFirstTouchTarget == null,表示沒有child正在處理事件,即ViewGroup正在處理事件
            if (actionMasked == MotionEvent.ACTION_DOWN
                    || mFirstTouchTarget != null) {
                // 檢查禁止攔截標記:FLAG_DISALLOW_INTERCEPT
                // 如果調用了requestDisallowInterceptTouchEvent()標記的話,則FLAG_DISALLOW_INTERCEPT會爲true。
                // 例如,ViewPager在處理觸摸事件的時候,就會調用requestDisallowInterceptTouchEvent()
                //     ,禁止它的父類對觸摸事件進行攔截
                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.
            // 第4步,檢查當前的觸摸事件是否被取消
            // 
            // (01) 對於ACTION_DOWN而言,mPrivateFlags的PFLAG_CANCEL_NEXT_UP_EVENT位肯定是0;因此,canceled=false。
            // (02) 當前的View或ViewGroup要被從父View中detach時,PFLAG_CANCEL_NEXT_UP_EVENT就會被設爲true;
            //      此時,它就不再接受觸摸事情。
            final boolean canceled = resetCancelNextUpFlag(this)
                    || actionMasked == MotionEvent.ACTION_CANCEL;

            // Update list of touch targets for pointer down, if needed.
            // 第5步,將觸摸事件分發給"當前ViewGroup的子View和子ViewGroup"
            // 
            // 如果觸摸"沒有被取消",同時也"沒有被攔截"的話,則將觸摸事件分發給它的子View和子ViewGroup。  
            //     如果當前ViewGroup的孩子有接受觸摸事件的話,則將該孩子添加到mFirstTouchTarget鏈表中。
            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) {
                    // 這是獲取觸摸事件的序號 以及 觸摸事件的id信息。
                    // (01) 對於ACTION_DOWN,actionIndex肯定是0
                    // (02) 而getPointerId()是獲取的該觸摸事件的id,並將該id信息保存到idBitsToAssign中。
                    //    這個觸摸事件的id是爲多指觸摸而添加的;對於單指觸摸,getActionIndex()返回的肯定是0;
                    //    而對於多指觸摸,第一個手指的id是0,第二個手指的id是1,第三個手指的id是2,...依次類推。
                    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.
                    // 清空這個手指之前的TouchTarget鏈表。
                    // 一個TouchTarget,相當於一個可以被觸摸的對象;它中記錄了接受觸摸事件的View
                    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;
                        // 獲取該ViewGroup包含的View和ViewGroup的數目,
                        // 然後遞歸遍歷ViewGroup的孩子,對觸摸事件進行分發。
                        // 遞歸遍歷ViewGroup的孩子:是指對於當前ViewGroup的所有孩子,都會逐個遍歷,並分發觸摸事件;
                        //   對於逐個遍歷到的每一個孩子,若該孩子是ViewGroup類型的話,則會遞歸到調用該孩子的孩子,...
                        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;
                            }

                            // 如果child可以接受觸摸事件,
                            // 並且觸摸座標(x,y)在child的可視範圍之內的話;
                            // 則繼續往下執行。否則,調用continue。
                            // child可接受觸摸事件:是指child的是可見的(VISIBLE);或者雖然不可見,但是位於動畫狀態。
                            if (!canViewReceivePointerEvents(child)
                                    || !isTransformedTouchPointInView(x, y, child, null)) {
                                ev.setTargetAccessibilityFocus(false);
                                continue;
                            }

                            // getTouchTarget()的作用是查找child是否存在於mFirstTouchTarget的單鏈表中。
                            // 是的話,返回對應的TouchTarget對象;否則,返回null。
                            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;
                            }
                            
                            // 重置child的mPrivateFlags變量中的PFLAG_CANCEL_NEXT_UP_EVENT位。
                            resetCancelNextUpFlag(child);
                            // 調用dispatchTransformedTouchEvent()將觸摸事件分發給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();
                                // 如果child能夠接受該觸摸事件,即child消費或者攔截了該觸摸事件的話;
                                // 則調用addTouchTarget()將child添加到mFirstTouchTarget鏈表的表頭,並返回表頭對應的TouchTarget
                                // 同時還設置alreadyDispatchedToNewTouchTarget爲true。
                                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();
                    }

                    // 如果newTouchTarget爲null,並且mFirstTouchTarget不爲null;
                    // 則設置newTouchTarget爲mFirstTouchTarget鏈表中第一個不爲空的節點。
                    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.
            // 第6步,進一步的對觸摸事件進行分發
            // 
            // (01) 如果mFirstTouchTarget爲null,意味着還沒有任何View來接受該觸摸事件;
            //   此時,將當前ViewGroup看作一個View;
            //   將會調用"當前的ViewGroup的父類View的dispatchTouchEvent()"對觸摸事件進行分發處理。
            //   即,會將觸摸事件交給當前ViewGroup的onTouch(), onTouchEvent()進行處理。
            // (02) 如果mFirstTouchTarget不爲null,意味着有ViewGroup的子View或子ViewGroup中,
            //   有可以接受觸摸事件的。那麼,就將觸摸事件分發給這些可以接受觸摸事件的子View或子ViewGroup。
            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.
            // 第7步:再次檢查取消標記,並進行相應的處理
            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);
            }
        }

        // mInputEventConsistencyVerifier是調試用的,不會理會
        if (!handled && mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onUnhandledEvent(ev, 1);
        }
        return handled;
    }

注意:第5步,即ViewGroup嘗試將觸摸事件分發給它的孩子。這只有在ACTION_DOWN的時候才發生。如果它的孩子接受了觸摸事件,則會調用addTouchTarget()將該孩子添加到mFirstTouchTarget鏈表中。 在ACTION_DOWN之後,傳遞ACTION_MOVE或ACTION_UP時,ViewGroup不會再執行第5步;而是在第6步中,直接遍歷mFirstTouchTarget鏈表,查找之前接受ACTION_DOWN的孩子,並將觸摸事件分配給這些孩子。
也就是說,如果ViewGroup的某個孩子沒有接受ACTION_DOWN事件;那麼,ACTION_MOVE和ACTION_UP等事件也一定不會分發給這個孩子!

/**
     * 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.
        // 檢測是否需要發送ACTION_CANCEL。
        // 如果cancel爲true 或者 action是ACTION_CANCEL;
        // 則設置消息爲ACTION_CANCEL,並將ACTION_CANCEL消息分發給對應的對象,並返回。
        // (01) 如果child是空,則將ACTION_CANCEL消息分發給當前ViewGroup;
        //      只不過會將ViewGroup看作它的父類View,調用View的dispatchTouchEvent()接口。
        // (02) 如果child不是空,調用child的dispatchTouchEvent()。
        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.
        // (01) 如果child是空,則將ViewGroup看作它的父類View,調用View的dispatchTouchEvent()接口。
        // (02) 如果child不是空,調用child的dispatchTouchEvent()。
        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;
    }

說明:dispatchTransformedTouchEvent()會對觸摸事件進行重新打包後再分發。
如果它的第三個參數child是null,則會將觸摸消息分發給ViewGroup自己,只不過此時是將ViewGroup看作一個View,即調用View的dispatchTouchEvent()進行消息分發。而View的dispatchTouchEvent()會將觸摸事件分發給onTouch(), onTouchEvent()進行處理。 如果它的第三個參數child不是null,則會調用child.dispatchTouchEvent()進行消息分發。而如果這個child是ViewGroup對象的話,它則又會遞歸的將消息分發給它的孩子。

2.2.2  ViewGroup中的事件分發流程圖

 

2.3 View事件的分發機制

2.3.1 View源碼分析

/**
     * 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) {
        // 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();
        }
        // 如果該View被遮蔽,並且該View在被遮蔽時不響應點擊事件;
        // 此時,返回false;不會執行onTouch()或onTouchEvent(),即過濾調用該點擊事件。
        // 否則,返回true。
        // 被遮蔽的意思是:該View不是位於頂部,有其他的View在它之上。
        if (onFilterTouchEventForSecurity(event)) {
            if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
                result = true;
            }
            //noinspection SimplifiableIfStatement
            ListenerInfo li = mListenerInfo;
            //當這個view的onClickListener不爲空且回調函數onTouch(this, event)返回true的時候,View.dispatchTouchEvent(MotionEvent event)就返回true
            if (li != null && li.mOnTouchListener != null
                    && (mViewFlags & ENABLED_MASK) == ENABLED
                    && li.mOnTouchListener.onTouch(this, event)) {
                result = true;
            }
            //然後如果前面事件沒有被消費,如果onTouchEvent(event)返回true,則View.dispatchTouchEvent(MotionEvent event)也返回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;
    }

    boolean isAccessibilityFocusedViewOrHost() {
        return isAccessibilityFocused() || (getViewRootImpl() != null && getViewRootImpl()
                .getAccessibilityFocusedHost() == this);
    }

注意:

1.View中的dispatchTouchEvent()會將事件傳遞給"自己的onTouch()", "自己的onTouchEvent()"進行處理。而且onTouch()的優先級比onTouchEvent()的優先級要高。

 2. onTouch()與onTouchEvent()都是View中用戶處理觸摸事件的API。onTouch是OnTouchListener接口中的函數,OnTouchListener接口需要用戶自己實現。onTouchEvent()是View自帶的接口,Android系統提供了默認的實現;當然,用戶可以重載該API。


3. onTouch()與onTouchEvent()有兩個不同之處:(01), onTouch()是View提供給用戶,讓用戶自己處理觸摸事件的接口。而onTouchEvent()是Android系統自己實現的接口。(02),onTouch()的優先級比onTouchEvent()的優先級更高。dispatchTouchEvent()中分發事件的時候,會先將事件分配給onTouch()進行處理,然後才分配給onTouchEvent()進行處理。 如果onTouch()對觸摸事件進行了處理,並且返回true;那麼,該觸摸事件就不會分配在分配給onTouchEvent()進行處理了。只有當onTouch()沒有處理,或者處理了但返回false時,纔會分配給onTouchEvent()進行處理。

/**
     * Implement this method to handle touch screen motion events.
     * <p>
     * If this method is used to detect click actions, it is recommended that
     * the actions be performed by implementing and calling
     * {@link #performClick()}. This will ensure consistent system behavior,
     * including:
     * <ul>
     * <li>obeying click sound preferences
     * <li>dispatching OnClickListener calls
     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
     * accessibility features are enabled
     * </ul>
     *
     * @param event The motion event.
     * @return True if the event was handled, false otherwise.
     */
    public boolean onTouchEvent(MotionEvent event) {
        final float x = event.getX();
        final float y = event.getY();
        final int viewFlags = mViewFlags;
        final int action = event.getAction();

        final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE
                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;

        if ((viewFlags & ENABLED_MASK) == DISABLED) {
            if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
                setPressed(false);
            }
            mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
            // A disabled view that is clickable still consumes the touch
            // events, it just doesn't respond to them.
            return clickable;
        }
         // 如果該View的mTouchDelegate不爲null的話,將觸摸消息分發給mTouchDelegate。
        // mTouchDelegate的默認值是null。
        if (mTouchDelegate != null) {
            if (mTouchDelegate.onTouchEvent(event)) {
                return true;
            }
        }
    
        // 如果View可以被點擊的話,則執行if裏面的內容。
        // 這其中涉及到的主要是獲取焦點,設置按下狀態,觸發onClick(), onLongClick()事件等等。
        if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
            switch (action) {
                case MotionEvent.ACTION_UP:
                    mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
                    if ((viewFlags & TOOLTIP) == TOOLTIP) {
                        handleTooltipUp();
                    }
                    if (!clickable) {
                        removeTapCallback();
                        removeLongPressCallback();
                        mInContextButtonPress = false;
                        mHasPerformedLongPress = false;
                        mIgnoreNextUpEvent = false;
                        break;
                    }
                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
                        // take focus if we don't have it already and we should in
                        // touch mode.
                        boolean focusTaken = false;
                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
                            focusTaken = requestFocus();
                        }

                        if (prepressed) {
                            // The button is being released before we actually
                            // showed it as pressed.  Make it show the pressed
                            // state now (before scheduling the click) to ensure
                            // the user sees it.
                            setPressed(true, x, y);
                        }

                        if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
                            // This is a tap, so remove the longpress check
                            removeLongPressCallback();

                            // Only perform take click actions if we were in the pressed state
                            if (!focusTaken) {
                                // Use a Runnable and post this rather than calling
                                // performClick directly. This lets other visual state
                                // of the view update before click actions start.
                                if (mPerformClick == null) {
                                    mPerformClick = new PerformClick();
                                }
                                if (!post(mPerformClick)) {
                                    performClickInternal();
                                }
                            }
                        }

                        if (mUnsetPressedState == null) {
                            mUnsetPressedState = new UnsetPressedState();
                        }

                        if (prepressed) {
                            postDelayed(mUnsetPressedState,
                                    ViewConfiguration.getPressedStateDuration());
                        } else if (!post(mUnsetPressedState)) {
                            // If the post failed, unpress right now
                            mUnsetPressedState.run();
                        }

                        removeTapCallback();
                    }
                    mIgnoreNextUpEvent = false;
                    break;

                case MotionEvent.ACTION_DOWN:
                    if (event.getSource() == InputDevice.SOURCE_TOUCHSCREEN) {
                        mPrivateFlags3 |= PFLAG3_FINGER_DOWN;
                    }
                    mHasPerformedLongPress = false;

                    if (!clickable) {
                        checkForLongClick(0, x, y);
                        break;
                    }

                    if (performButtonActionOnTouchDown(event)) {
                        break;
                    }

                    // Walk up the hierarchy to determine if we're inside a scrolling container.
                    boolean isInScrollingContainer = isInScrollingContainer();

                    // For views inside a scrolling container, delay the pressed feedback for
                    // a short period in case this is a scroll.
                    if (isInScrollingContainer) {
                        mPrivateFlags |= PFLAG_PREPRESSED;
                        if (mPendingCheckForTap == null) {
                            mPendingCheckForTap = new CheckForTap();
                        }
                        mPendingCheckForTap.x = event.getX();
                        mPendingCheckForTap.y = event.getY();
                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
                    } else {
                        // Not inside a scrolling container, so show the feedback right away
                        setPressed(true, x, y);
                        checkForLongClick(0, x, y);
                    }
                    break;

                case MotionEvent.ACTION_CANCEL:
                    if (clickable) {
                        setPressed(false);
                    }
                    removeTapCallback();
                    removeLongPressCallback();
                    mInContextButtonPress = false;
                    mHasPerformedLongPress = false;
                    mIgnoreNextUpEvent = false;
                    mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
                    break;

                case MotionEvent.ACTION_MOVE:
                    if (clickable) {
                        drawableHotspotChanged(x, y);
                    }

                    // Be lenient about moving outside of buttons
                    if (!pointInView(x, y, mTouchSlop)) {
                        // Outside button
                        // Remove any future long press/tap checks
                        removeTapCallback();
                        removeLongPressCallback();
                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
                            setPressed(false);
                        }
                        mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
                    }
                    break;
            }

            return true;
        }

        return false;
    }

 

2.3.1 View的事件分發流程圖

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