View的事件分發機制最新源碼剖析

先拋出幾個問題

1:觸發View事件dispatchTouchEvent與onTouchEvent那個函數先執行?
2:onTouch消費事件的具體含義是什麼?
3:onTouch,onClick回調方法的先後執行順序?

先建立這樣一個佈局:
這裏寫圖片描述

Button分別監聽onTouchListener & onClickListener

        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sb.append("onclick is called!" + "\n");
            }
        });
        button1.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                sb.append("ontouch is called! event = " + event.getAction() + "\n");
                return isCheck;
            }
        });

isCheck由Checkbox控制默認爲false;
默認情況下點擊button,打印日誌如下:

02-19 10:20:48.154 19082-19082/com.example.hongentao.touchdemo I/ViewActivity: ontouch is called! event = 0
02-19 10:20:48.154 19082-19082/com.example.hongentao.touchdemo I/ViewActivity: ontouch is called! event = 2
02-19 10:20:48.154 19082-19082/com.example.hongentao.touchdemo I/ViewActivity: ontouch is called! event = 2
02-19 10:20:48.154 19082-19082/com.example.hongentao.touchdemo I/ViewActivity: ontouch is called! event = 1
02-19 10:20:48.154 19082-19082/com.example.hongentao.touchdemo I/ViewActivity: onclick is called

選擇CheckBox,消費掉OnTouch事件,打印日誌如下:

02-19 10:23:43.694 19082-19082/com.example.hongentao.touchdemo I/ViewActivity: ontouch is called! event = 0
02-19 10:23:43.694 19082-19082/com.example.hongentao.touchdemo I/ViewActivity: ontouch is called! event = 2
02-19 10:23:43.694 19082-19082/com.example.hongentao.touchdemo I/ViewActivity: ontouch is called! event = 2
02-19 10:23:43.694 19082-19082/com.example.hongentao.touchdemo I/ViewActivity: ontouch is called! event = 1

查看打印日誌,發現消費掉Ontouch事件後(也就是將返回值設爲true),onClick事件沒有得到執行。

那到底是什麼原因導致的呢?

打開源碼我們來分析一下:

Button是自定義的View,代碼如下:

public class MyButton extends Button {
    private String TAG = MyButton.class.getSimpleName();

    public MyButton(Context context) {
        super(context);
    }

    public MyButton(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        Log.i(TAG, "disPatchTouchEvent is called!");
        return super.dispatchTouchEvent(event);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        Log.i(TAG, "onTouchEvent is called!");
        return super.onTouchEvent(event);
    }

}

這裏打印日誌發現永遠都是dispatchTouchEvent事件先執行,只要觸發View的任何事件都會首先觸發該方法。

源碼爲api-23, 老版本源碼略有不同

我們找找dispatchTouchEvent到底在哪裏?
這裏寫圖片描述
分別在Button,TextView中都沒有找到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)) {
            //noinspection SimplifiableIfStatement
            ListenerInfo li = mListenerInfo;
            if (li != null && li.mOnTouchListener != null
                    && (mViewFlags & ENABLED_MASK) == ENABLED
                    && li.mOnTouchListener.onTouch(this, event)) {
                result = 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;
    }

分析關鍵代碼:

if (onFilterTouchEventForSecurity(event)) {
            //noinspection SimplifiableIfStatement
            ListenerInfo li = mListenerInfo;
            if (li != null && li.mOnTouchListener != null
                    && (mViewFlags & ENABLED_MASK) == ENABLED
                    && li.mOnTouchListener.onTouch(this, event)) {
                result = true;
            }

            if (!result && onTouchEvent(event)) {
                result = true;
            }
        }

onFilterTouchEventForSecurity(event)是判斷改點擊事件是否應該被傳遞,然後進入下一級判斷條件,分別爲四級判斷條件
1:li != null
2: li.mOntouchListener != null
3:(mViewFlags & ENABLED_MASK) == ENABLED
4:li.mOnTouchListener.onTouch(this, event)

首先分析第一個判斷條件:
ListenerInfo li = mListenerInfo;
mListenerInfo在那裏被賦值的呢?
跟蹤源碼:

    ListenerInfo getListenerInfo() {
        if (mListenerInfo != null) {
            return mListenerInfo;
        }
        mListenerInfo = new ListenerInfo();
        return mListenerInfo;
    }
    public void setOnClickListener(@Nullable OnClickListener l) {
        if (!isClickable()) {
            setClickable(true);
        }
        getListenerInfo().mOnClickListener = l;
    }

在Button setOnclickListener監聽事件的時候,調用getListenerInfo方法,getListenerInfo就是一個單例事件,從而li被賦值。

分析第二個判斷條件:
li.mOntouchListener != null
這個又是什麼鬼?
來來來,繼續看源碼

 /**
     * Register a callback to be invoked when a touch event is sent to this view.
     * @param l the touch listener to attach to this view
     */
    public void setOnTouchListener(OnTouchListener l) {
        getListenerInfo().mOnTouchListener = l;
    }

通過查看源碼,mTouchListener就是在setOntouchListener的時候被賦值的,一目瞭然。

再來看第三個判斷條件:
(mViewFlags & ENABLED_MASK) == ENABLED
這個比較簡單,就是判斷當前的View是否是可點擊的。

第四個判斷條件爲:
li.mOnTouchListener.onTouch(this, event)
這個更直接,直接獲取onTouch的返回值:

借用這四種判斷條件顯而易見可以分析出,當Button消費掉ontouch事件之後,直接renturn true,onclick不會被執行。 而如果ontouch沒有被消費,通過源碼onclick肯定是在onTouchEvent(event)事件中被執行。

查看下源碼:

 /**
     * 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();

        if ((viewFlags & ENABLED_MASK) == DISABLED) {
            if (action == 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)
                    || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE);
        }

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

        if (((viewFlags & CLICKABLE) == CLICKABLE ||
                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) ||
                (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) {
            switch (action) {
                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.
                        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)) {
                                    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();
                    }
                    mIgnoreNextUpEvent = false;
                    break;

                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();
                    mInContextButtonPress = false;
                    mHasPerformedLongPress = false;
                    mIgnoreNextUpEvent = false;
                    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;
    }

源碼好長直接挑重點:
當Event爲 ACTION_UP之後,經過一系列的判斷會進入該段代碼:

   if (!post(mPerformClick)) {performClick();}                            

進入performClick源碼中看下:

public boolean performClick() {
        final boolean result;
        final ListenerInfo li = mListenerInfo;
        if (li != null && li.mOnClickListener != null) {
            playSoundEffect(SoundEffectConstants.CLICK);
            li.mOnClickListener.onClick(this);
            result = true;
        } else {
            result = false;
        }

        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
        return result;
    }

果然看見了onclick事件被執行,現在答案也一一被解答了。

現在分別解答下開篇提出的三個問題:

1:觸發View事件dispatchTouchEvent與onTouchEvent那個函數先執行?
答:只要是觸發View的任何事件,都會首先觸發dispatchTouchEvent事件。
2:onTouch消費事件的具體含義是什麼?
答:ouTouch消費事件後,後續註冊的事件回調都不會被執行,例如onClick。
3:onTouch,onClick回調方法的先後執行順序?
答:分兩種情況:1:onTouch消費掉事件, onTouch事件會被執行,onClick事件不會被執行。 2:onTouch沒有消費掉事件,onTouch先執行,onCLick事件後執行。

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