Android觸摸事件源碼分析:Activity->ViewGroup->View

Activity中

當屏幕有touch事件時,首先調用Activity的dispatchTouchEvent方法

 /**
     * 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) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            onUserInteraction();
        }
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
}
只有ACTION_DOWN事件派發時調運了onUserInteraction方法,直接跳進去可以看見是一個空方法。接着往下看

首先分析Activity的attach方法可以發現getWindow()返回的就是PhoneWindow對象(PhoneWindow爲抽象Window的實現子類),那就簡單了,也就相當於PhoneWindow類的方法,而PhoneWindow類實現於Window抽象類,所以先看下Window類中抽象方法的定義,如下:

<span style="font-size:24px;">/**
     * Used by custom windows, such as Dialog, to pass the touch screen event
     * further down the view hierarchy. Application developers should
     * not need to implement or call this.
     *用戶不需要重寫實現的方法,實質也不能,在Activity中沒有提供重寫的機會,因爲Window是以組</span><pre name="code" class="java"><span style="font-size:24px;">*</span><span style="font-family: Arial, Helvetica, sans-serif;"><span style="font-size:18px;">合模式與Activity建立關係的</span></span>
*/ public abstract boolean superDispatchTouchEvent(MotionEvent event);


PhoneWindow裏看下Window抽象方法的實現:

 @Override
    public boolean superDispatchTouchEvent(MotionEvent event) {
        return mDecor.superDispatchTouchEvent(event);
 }
這裏出現了mDecor變量,是啥?其實是DecorView的實例,有人會問DecorView又是啥?

在PhoneWindow類裏發現,mDecor是DecorView類的實例,同時DecorView是PhoneWindow的內部類。最驚人的發現是DecorView extends FrameLayout implements RootViewSurfaceTaker,看見沒有?它是一個真正Activity的root view,它繼承了FrameLayout。
不知道大家是不是熟悉Android App開發技巧中關於UI佈局優化使用的SDK工具Hierarchy Viewer,打開的時候在最上面會有個DecorView$PhoneWindow的框框

Activity中setContentView時,把我們編寫的xmlLayout文件放置在一個id爲content的FrameLayout的佈局(DecorView)中,這也就是爲啥Activity的setContentView方法叫set content view了,就是把我們的xml放入了這個id爲content的FrameLayout中


講完了DecorView,我們在來看看mDecor.superDispatchTouchEvent(event):

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


上面PhoneWindow的superDispatchTouchEvent直接返回了DecorView的superDispatchTouchEvent,而DecorView又是FrameLayout的子類,FrameLayout又是ViewGroup的子類,touch事件就被分發到的我們們定義的xmlLayout佈局中。接下來分析ViewGroup的事件分發。

Activity的dispatchTouchEvent方法的if (getWindow().superDispatchTouchEvent(ev))本質執行的是一個ViewGroup的dispatchTouchEvent方法(這個ViewGroup是Activity特有的root view,也就是id爲content的FrameLayout佈局)

在Activity的觸摸屏事件派發中:Activity,PhoneWindow,DecorView,ViewGroup
1,首先會觸發Activity的dispatchTouchEvent方法。
2,dispatchTouchEvent方法中如果是ACTION_DOWN的情況下會接着觸發onUserInteraction方法。
3,接着在dispatchTouchEvent方法中會通過Activity的root View(id爲content的FrameLayout),實質是ViewGroup,通過super.dispatchTouchEvent把touchevent派發給各個activity的子view,也就是我們再Activity.onCreat方法中setContentView時設置的view。
4,若Activity下面的子view攔截了touchevent事件(返回true)則Activity.onTouchEvent方法就不會執行。

ViewGroup中

既然Activity中的DecorView是ViewGroup的子類調用了dispatchTouchEvent方法,來看看這個方法:

 @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        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;
/*清除以往的Touch狀態然後開始新的手勢。在這裏你會發現cancelAndClearTouchTargets(ev)方法中有一個非常重要的操作就是將mFirstTouchTarget設置爲了null(剛開始分析大眼瞄一眼沒留意,結果越往下看越迷糊,所以這個是分析ViewGroup的dispatchTouchEvent方法第一步中重點要記住的一個地方),接着在resetTouchState()方法中重置Touch狀態標識。*/
            // 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) {// 說明當事件爲ACTION_DOWN或者mFirstTouchTarget不爲null(即已經找到能夠接收touch事件的目標組件)時if成立,否則if不成立,然後將intercepted設置爲true,也即攔截事件                
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
                if (!disallowIntercept) {  // 如果沒有禁止攔截,就調用onInterceptTouchEvent方法,touch事件就繼續傳遞給子View,默認不攔截
                    intercepted = onInterceptTouchEvent(ev);
                    ev.setAction(action); // restore action in case it was changed存儲動作以防止它改變
                } else {
                    intercepted = false; // 如果禁止攔截,intercepted就是false,touch事件就繼續傳遞給子View
                }
            } else {
                // There are no touch targets and this action is not an initial down
                // so this view group continues to intercept touches.如果沒有touch目標組件和down事件,這個viewgroup就是繼續攔截touch
                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.檢查取消,然後將結果賦值給局部boolean變量canceled
            final boolean canceled = resetCancelNextUpFlag(this)
                    || actionMasked == MotionEvent.ACTION_CANCEL;

            // Update list of touch targets for pointer down, if needed. 默認是true,作用是是否把事件分發給多個子View
            final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;
            TouchTarget newTouchTarget = null;
            boolean alreadyDispatchedToNewTouchTarget = false;
            if (!canceled && !intercepted) { // 如果沒有被取消也沒有被攔截,就開始進行分發事件了

                // If the event is targeting accessiiblity 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) { // childrenCount個數是否不爲0且新的touch target是空,目的就是爲了找到touch target
                        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();//子View的list集合preorderedList
                        final boolean customOrder = preorderedList == null
                                && isChildrenDrawingOrderEnabled();
                        final View[] children = mChildren;
                        for (int i = childrenCount - 1; i >= 0; i--) {//for循環i從childrenCount - 1開始遍歷到0,倒序遍歷所有的子view
                            final int childIndex = customOrder
                                    ? getChildDrawingOrder(childrenCount, i) : i;
                            final View child = (preorderedList == null)
                                    ? children[childIndex] : preorderedList.get(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); //這一句很重要,通過getTouchTarget去查找當前子View是否在mFirstTouchTarget.next這條target鏈中的某一個target中,如果在則返回這個target,否則返回null
                            if (newTouchTarget != null) {//找到了接收Touch事件的子View,即newTouchTarget,那麼,既然已經找到了,所以執行break跳出for循環
                                // 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);
                         /**
                          *調用方法dispatchTransformedTouchEvent()將Touch事件傳遞給特定的子View。該方法十分重要,在該方法中爲一個遞歸調用,會遞歸調用                             dispatchTouchEvent()方法。在dispatchTouchEvent()中如果子View爲ViewGroup並且Touch沒有被攔截那麼遞歸調用dispatchTouchEvent(),如果子View爲View那麼就會調用其onTouchEvent()。dispatchTransformedTouchEvent方法如果返回true則表示子View消費掉該事件,同時進入該if判斷。滿足if語句後重要的操作有:

1,給newTouchTarget賦值;
2,給alreadyDispatchedToNewTouchTarget賦值爲true;
3,執行break,因爲該for循環遍歷子View判斷哪個子View接受Touch事件,既然已經找到了就跳出該外層for循環;
                          */
                            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;
                    }
                }
            }
           /**
  *因爲在dispatchTransformedTouchEvent()會調用遞歸調用dispatchTouchEvent()和onTouchEvent(),所以dispatchTransformedTouchEvent()的返回值實際上是由
onTouchEvent()決定的。簡單地說onTouchEvent()是否消費了Touch事件的返回值決定了dispatchTransformedTouchEvent()的返回值,從而決定mFirstTouchTarget是否爲null,進一步決定了ViewGroup   是否處理Touch事件
*/
            // 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;
    }

ViewGroup中的onInterceptTouchEvent

/**
     * Implement this method to intercept all touch screen motion events.  This
     * allows you to watch events as they are dispatched to your children, and
     * take ownership of the current gesture at any point.
     *實現這個方法攔截屏幕的所有觸摸事件,這就允許你觀察這些事件被分發給你的孩子,在任何一個點掌控當前手勢
     * <p>Using this function takes some care, as it has a fairly complicated
     * interaction with {@link View#onTouchEvent(MotionEvent)
     * View.onTouchEvent(MotionEvent)}, and using it requires implementing
     * that method as well as this one in the correct way.  Events will be
     * received in the following order:
     *使用這個函數要小心,它和View的onTouchEvent有十分複雜的交互,事件能夠按照下列的順序被收到:
     * <ol>
     * <li> You will receive the down event here.1,你將先收到down事件
     * <li> The down event will be handled either by a child of this view
     * group, or given to your own onTouchEvent() method to handle; this means
     * you should implement onTouchEvent() to return true, so you will
     * continue to see the rest of the gesture (instead of looking for
     * a parent view to handle it).  Also, by returning true from
     * onTouchEvent(), you will not receive any following
     * events in onInterceptTouchEvent() and all touch processing must
     * happen in onTouchEvent() like normal.
     *  2,down事件要麼被子View的handle,要麼被這個viewgroup的onTouchEvent方法處理
     * <li> For as long as you return false from this function, each following
     * event (up to and including the final up) will be delivered first here
     * and then to the target's onTouchEvent().
* 3,只要onInterceptTouchEvent返回false,後面的每個事件都會繼續分發到touch target執行target's onTouchEvent()
     * <li> If you return true from here, you will not receive any
     * following events: the target view will receive the same event but
     * with the action {@link MotionEvent#ACTION_CANCEL}, and all further
     * events will be delivered to your onTouchEvent() method and no longer
     * appear here.
     * 4,onInterceptTouchEvent返回true, 交給這個ViewGroup的onTouchEvent處理。
     * </ol>
     *
     * @param ev The motion event being dispatched down the hierarchy.
     * @return Return true to steal motion events from the children and have
     * them dispatched to this ViewGroup through onTouchEvent().
     * The current target will receive an ACTION_CANCEL event, and no further
     * messages will be delivered here.
     */
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return false;
    }
看到了吧,這個方法算是ViewGroup不同於View特有的一個事件派發調運方法。在源碼中可以看到這個方法實現很簡單,但是有一堆註釋。其實上面分析了,如果ViewGroup的onInterceptTouchEvent返回false就不阻止事件繼續傳遞派發,否則阻止傳遞派發。

如上就是所有ViewGroup關於觸摸屏事件的傳遞機制源碼分析。具體總結如下:
1,Android事件派發是先傳遞到最頂級的ViewGroup,再由ViewGroup遞歸傳遞到View的。
2,在ViewGroup中可以通過onInterceptTouchEvent方法對事件傳遞進行攔截,3,onInterceptTouchEvent方法

   1)返回true   代表不允許事件繼續向子View傳遞,則交給這個ViewGroup的onTouchEvent處理

   2)返回false 代表不對事件進行攔截,默認返回false,則交給子View的dispatchTouchEvent方法處理
4,事件傳遞到子view 的 dispatchTouchEvent方法中,通過方法傳遞到當前View的onTouchEvent方法中:
(1)如果返回true,那麼這個事件就會止於該view。
(2)如果返回 false ,那麼這個事件會從這個子view 往上傳遞,而且都是傳遞到父View的onTouchEvent 來接收。

(3)如果傳遞到ViewGroup的 onTouchEvent 也返回 false 的話,則繼續傳遞到Activity的onTouchEvent中,如果還是false,則這個事件就會“消失“;事件向上傳遞到中間的任何onTouchEvent方法中,如果返回true,則事件被消費掉,不會再傳遞。

View中觸摸消息機制:

在Android中你只要觸摸控件首先都會觸發控件的dispatchTouchEvent方法(其實這個方法一般都沒在具體的控件類中,而在他的父類View中),所以我們先來看下View的dispatchTouchEvent方法

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

        if (onFilterTouchEventForSecurity(event)) { // 判斷當前View是否沒被遮住
            //noinspection SimplifiableIfStatement ListenerInfo局部變量,ListenerInfo是View的靜態內部類,用來定義一堆關於View的XXXListener等方法
            ListenerInfo li = mListenerInfo;
           /**一,首先判斷是不是設置onTouch監聽器,onTouch的返回值
* 首先li對象自然不會爲null, li.mOnTouchListener是不是null取決於控件(View)是否設置setOnTouchListener監聽
* 接着通過位與運算確定控件(View)是不是ENABLED 的,默認控件都是ENABLED 的
            *  接着判斷onTouch的返回值是不是true
            */
            if (li != null && li.mOnTouchListener != null
                    && (mViewFlags & ENABLED_MASK) == ENABLED
                    && li.mOnTouchListener.onTouch(this, event)) {
                result = true; //如果設置了onTouchListener,並且onTouch返回時true,result就是true,下一句if就不執行了,onTouchEvent和onClick就不執行了
            }
            //上面的執行了result等於true,這句就不執行了。如果result是false,就執行onTouchEvent,onTouchEvent中有執行onClick的步驟
            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;
    }
如果
if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED && li.mOnTouchListener.onTouch(this, event))
語句有一個爲false則
if (!result && onTouchEvent(event))
就會執行,如果onTouchEvent(event)返回false則dispatchTouchEvent返回false,否則返回true。
控件觸摸就會調運dispatchTouchEvent方法,而在dispatchTouchEvent中先執行的是onTouch方法,所以驗證了實例結論總結中的onTouch優先於onClick執行道理。如果控件是ENABLE且在onTouch方法裏返回了true則dispatchTouchEvent方法也返回true,不會再繼續往下執行;

     反之,onTouch返回false則會繼續向下執行onTouchEvent方法,且dispatchTouchEvent的返回值與onTouchEvent返回值相同。
所以依據這個結論和上面實例打印結果你指定已經大膽猜測認爲onClick一定與onTouchEvent有關係?

總結結論
在View的觸摸屏傳遞機制中通過分析dispatchTouchEvent方法源碼我們會得出如下基本結論:
1,觸摸控件(View)首先執行dispatchTouchEvent方法。
2,在dispatchTouchEvent方法中先執行onTouch方法,後執行onClick方法(onClick方法在onTouchEvent中執行,下面會分析)。
3,如果控件(View)的onTouch返回false或者mOnTouchListener爲null(控件沒有設置setOnTouchListener方法)或者控件不是enable的情況下會調運onTouchEvent,dispatchTouchEvent返回值與onTouchEvent返回一樣。
4,如果控件不是enable的設置了onTouch方法也不會執行,只能通過重寫控件的onTouchEvent方法處理(上面已經處理分析了),dispatchTouchEvent返回值與onTouchEvent返回一樣。
5,如果控件(View)是enable且onTouch返回true情況下,dispatchTouchEvent直接返回true,不會調用onTouchEvent方法。
View的dispatchTouchEvent方法中調運的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;

        if ((viewFlags & ENABLED_MASK) == DISABLED) { // 組件設置的disabled,組件不可用,那就直接返回了
            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
                setPressed(false);
            }
            // A disabled view that is clickable still consumes the touch
            // events, it just doesn't respond to them.
            return (((viewFlags & CLICKABLE) == CLICKABLE ||
                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
        }

        if (mTouchDelegate != null) {
            if (mTouchDelegate.onTouchEvent(event)) {
                return true;
            }
        }

        if (((viewFlags & CLICKABLE) == CLICKABLE ||
                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) { //如果組件是enabled且可點擊,或者可長點擊
            switch (event.getAction()) {
                case MotionEvent.ACTION_UP:
                    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. 
// 首先判斷了是否按下過,同時是不是可以得到焦點,然後嘗試獲取焦點,然後判斷如果不是longPressed則通過post在UI Thread中執行一個PerformClick的Runnable,也就是performClick方法。
                        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) {
                            // 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.
// 使用post一個Runnable的PerformClick的任務類而不是直接調用performClick的方法。
                                if (mPerformClick == null) {
                                    mPerformClick = new PerformClick();
                                }
                                if (!post(mPerformClick)) {
                                    performClick();// 終於找到了,onClick方法在performClick的函數中
                                }
                            }
                        }

                        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();
                    }
                    break;
                // ACTION_DOWN與ACTION_MOVE都進行了一些必要的設置與置位
                case MotionEvent.ACTION_DOWN:
                    mHasPerformedLongPress = false;

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

                case MotionEvent.ACTION_CANCEL:
                    setPressed(false);
                    removeTapCallback();
                    removeLongPressCallback();
                    break;

                case MotionEvent.ACTION_MOVE:
                    drawableHotspotChanged(x, y);

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

                            setPressed(false);
                        }
                    }
                    break;
            }

            return true;
        }

        return false;
    }

<span style="font-size:24px;">/**
     * Call this view's OnClickListener, if it is defined.  Performs all normal
     * actions associated with clicking: reporting accessibility event, playing
     * a sound, etc.
     *調用這個view的OnClickListener方法。
     * @return True there was an assigned OnClickListener that was called, false
     *         otherwise is returned.
     */
    public boolean performClick() {
        final boolean result;
        final ListenerInfo li = mListenerInfo;
        if (li != null && li.mOnClickListener != null) { // 和dispatchTouchEvent中的判斷一樣,li自然不是null,如果設置了OnclickListener那麼 li.mOnClickListener也不爲空

            playSoundEffect(SoundEffectConstants.CLICK);
            li.mOnClickListener.onClick(this); // 這個是重點!!!!!,執行這個View的Onclick方法,返回true
            result = true;
        } else {
            result = false;
        }

        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
        return result;
    }
</span>

猜的沒錯onClick就在onTouchEvent中執行的,而且是在onTouchEvent的ACTION_UP事件中執行的

總結結論
1,onTouchEvent方法中會在ACTION_UP分支中觸發onClick的監聽。
2,當dispatchTouchEvent在進行事件分發的時候,只有前一個action返回true,纔會觸發下一個action。

參考:http://blog.csdn.net/yanbober/article/details/45887547

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