1. 程式人生 > >Android 原始碼解析View的touch事件分發機制

Android 原始碼解析View的touch事件分發機制

概述

本篇主要分析的是touch事件的分發機制,網上關於這個知識點的分析文章非常多。但是還是想通過結合自身的總結,來加深自己的理解。對於事件分發機制,我將使用兩篇文章對其進行分析,一篇是針對View的事件分發機制解析,一篇是針對ViewGroup的事件分發機制解析。本片是對View的事件分發機制進行解析,主要採用案例結合原始碼的方式來進行分析。

前言

在分析事件分發機制之前,我們先來學習一下基本的知識點,以便後面的理解。
View中有兩個關鍵方法參與到Touch事件分發
dispatchTouchEvent(MotionEvent event) 和 onTouchEvent(MotionEvent event)
所有Touch事件型別都被封裝在物件MotionEvent中,包括ACTION_DOWN,ACTION_MOVE,ACTION_UP等等。
每個執行動作必須執行完一個完整的流程,再繼續進行下一個動作。比如:ACTION_DOWN事件發生時,必須等這個事件的分發流程執行完(包括該事件被提前消費),才會繼續執行ACTION_MOVE或者ACTION_UP的事件。

案例分析

為了能夠清楚的監視事件的分發過程,我們採用自定義View的形式,檢視內部的方法執行過程。
上程式碼:

package com.yuminfeng.touch;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.Button;

public class MyButton extends Button {

    public
MyButton(Context context, AttributeSet attrs) { super(context, attrs); } @Override public boolean dispatchTouchEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: Log.i("yumf", "MyButton=====dispatchTouchEvent ACTION_DOWN"
); break; case MotionEvent.ACTION_UP: Log.i("yumf", "MyButton=====dispatchTouchEvent ACTION_UP"); break; } return super.dispatchTouchEvent(event); } @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: Log.i("yumf", "MyButton=====onTouchEvent ACTION_DOWN"); break; case MotionEvent.ACTION_UP: Log.i("yumf", "MyButton=====onTouchEvent ACTION_UP"); break; } return super.onTouchEvent(event); } }

在XML佈局中引用該控制元件,非常簡單。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.yuminfeng.myviewpager.FirstActivity" >

    <com.yuminfeng.touch.MyButton
        android:id="@+id/mybutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</RelativeLayout>

以上程式碼都非常簡單,沒有什麼邏輯,就是重寫Button的dispatchTouchEvent和onTouchEvent的方法,然後引用該控制元件即可。
然後執行程式碼,檢視日誌列印,如下:
這裡寫圖片描述
由此看到,當點選控制元件時,首先執行的是dispatchTouchEvent方法,然後再執行onTouchEvent的方法。
如果此時我們修改dispatchTouchEvent的返回值為true時(預設為false),那麼onTouchEvent方法便不再執行,如下:
這裡寫圖片描述
流程示意圖如下:
這裡寫圖片描述

接著我們恢復之前的返回值false,繼續讓mybutton設定一個setOnTouchListener監聽事件,關鍵程式碼如下:

     mybutton = (Button) findViewById(R.id.mybutton);

        mybutton.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    Log.i("yumf", "Activity=====onTouch ACTION_DOWN");
                    break;

                case MotionEvent.ACTION_UP:
                    Log.i("yumf", "Activity=====onTouch ACTION_UP");
                    break;
                }
                return false;
            }
        });

執行後,日誌列印如下:
這裡寫圖片描述
由此我們可以看到,首先執行方法dispatchTouchEvent,然後再執行OnTouchListener中onTouch方法,最後執行onTouchEvent方法。
同上,如果我們繼續修改dispatchTouchEvent的返回值為true時,那麼後面的方法onTouch,onTouchEvent均不執行。
如果我們修改onTouch的返回值為true,那麼後面的onTouchEvent事件就不會執行了。
流程示意圖如下:
這裡寫圖片描述
如上,恢復預設返回值false,然後在button上設定一個監聽點選事件,程式碼如下:

     mybutton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Log.i("yumf", "Activity=====onClick");
            }
        });

執行後,檢視日誌列印資訊,如下:
這裡寫圖片描述
由此我們可以知道,在完整的事件結束之後(從ACTION_DOWN開始,到ACTION_UP結束),這時才會去執行button的onClick方法。
綜合以上所述,View在處理Touch事件時,都是從dispatchTouchEvent方法開始的,因此我們在分析原始碼時,可以從該方法入手。

原始碼閱讀

我們當前的MyButton是繼承自Button,而Button又是繼承自TextView,TextView繼承自View,逐步往上檢視,可以發現父類的dispatchTouchEvent方法,就是View的dispatchTouchEvent方法。如下:

   /**
     * 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) {
        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 (mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
        }

通過檢視mInputEventConsistencyVerifier,得知這段程式碼主要是用來除錯的,可以不用關注。接著繼續檢視下一段程式碼

        final int actionMasked = event.getActionMasked();
        if (actionMasked == MotionEvent.ACTION_DOWN) {
            // Defensive cleanup for new gesture
            stopNestedScroll();
        }

當執行ACTION_DOWN事件時,進入方法stopNestedScroll()中,進入該方法中

 /**
     * Stop a nested scroll in progress.
     *
     * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p>
     *
     * @see #startNestedScroll(int)
     */
    public void stopNestedScroll() {
        if (mNestedScrollingParent != null) {
            mNestedScrollingParent.onStopNestedScroll(this);
            mNestedScrollingParent = null;
        }
    }

該方法主要是用來停止View的滑動,當一個滾動的view不是當前進行接收事件的View時不會受到影響。下面的一段程式碼是關鍵的程式碼,我們來看看

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

上面的程式碼中,首先根據安全策略過濾event,來確定是否響應這個事件,返回true表示響應。響應該事件後,將mListenerInfo賦值給ListenerInfo物件。那麼這個mListenerInfo到底是什麼呢,我們現在來分析一下mListenerInfo的初始化
首先,我們可以在View的屬性中,能看到該物件的引用:

ListenerInfo mListenerInfo;

接著,在getListenerInfo()方法中初始化:

    ListenerInfo getListenerInfo() {
        if (mListenerInfo != null) {
            return mListenerInfo;
        }
        mListenerInfo = new ListenerInfo();
        return mListenerInfo;
    }

最後,在為該View的物件設定監聽器時,會將對應的監聽器物件返回賦值給mListenerInfo物件,如下:

/**
     * Register a callback to be invoked when focus of this view changed.
     *
     * @param l The callback that will run.
     */
    public void setOnFocusChangeListener(OnFocusChangeListener l) {
        getListenerInfo().mOnFocusChangeListener = l;
    }

    /**
     * Returns the focus-change callback registered for this view.
     *
     * @return The callback, or null if one is not registered.
     */
    public OnFocusChangeListener getOnFocusChangeListener() {
        ListenerInfo li = mListenerInfo;
        return li != null ? li.mOnFocusChangeListener : null;
    }

    /**
     * Register a callback to be invoked when this view is clicked. If this view is not
     * clickable, it becomes clickable.
     *
     * @param l The callback that will run
     *
     * @see #setClickable(boolean)
     */
    public void setOnClickListener(OnClickListener l) {
        if (!isClickable()) {
            setClickable(true);
        }
        getListenerInfo().mOnClickListener = l;
    }

    /**
     * Register a callback to be invoked when this view is clicked and held. If this view is not
     * long clickable, it becomes long clickable.
     *
     * @param l The callback that will run
     *
     * @see #setLongClickable(boolean)
     */
    public void setOnLongClickListener(OnLongClickListener l) {
        if (!isLongClickable()) {
            setLongClickable(true);
        }
        getListenerInfo().mOnLongClickListener = l;
    }

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

如上,其實裡面涉及的方法非常多,我只抽出了幾個常見的方法,如:setOnClickListener,setOnTouchListener等。
所以說當我們給View的物件設定監聽器時,通過回撥的方式,最後都會賦值到mListenerInfo物件中。mListenerInfo類裡面包含了許多的監聽器型別,如下:

    static class ListenerInfo {
        /**
         * Listener used to dispatch focus change events.
         * This field should be made private, so it is hidden from the SDK.
         * {@hide}
         */
        protected OnFocusChangeListener mOnFocusChangeListener;

        /**
         * Listeners for layout change events.
         */
        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;

        /**
         * Listeners for attach events.
         */
        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;

        /**
         * Listener used to dispatch click events.
         * This field should be made private, so it is hidden from the SDK.
         * {@hide}
         */
        public OnClickListener mOnClickListener;

        /**
         * Listener used to dispatch long click events.
         * This field should be made private, so it is hidden from the SDK.
         * {@hide}
         */
        protected OnLongClickListener mOnLongClickListener;

        /**
         * Listener used to build the context menu.
         * This field should be made private, so it is hidden from the SDK.
         * {@hide}
         */
        protected OnCreateContextMenuListener mOnCreateContextMenuListener;

        private OnKeyListener mOnKeyListener;

        private OnTouchListener mOnTouchListener;

        private OnHoverListener mOnHoverListener;

        private OnGenericMotionListener mOnGenericMotionListener;

        private OnDragListener mOnDragListener;

        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;

        OnApplyWindowInsetsListener mOnApplyWindowInsetsListener;
    }

完成了監聽器型別的賦值後,我們分析繼續下面的程式碼邏輯:

        if (li != null && li.mOnTouchListener != null
                    && (mViewFlags & ENABLED_MASK) == ENABLED
                    && li.mOnTouchListener.onTouch(this, event)) {
                result = true;
            }

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

這裡在if條件裡面我們看到了一個屬性的方法li.mOnTouchListener.onTouch(this, event),這就是我們在Activity中設定的setOnTouchListener中,重寫的onTouch方法。當返回為true時,result = true,這時便不執行下面程式碼中的onTouchEvent(event)方法。result 為false時,才執行onTouchEvent(event)方法。這段關鍵性的程式碼中,對應了我之前所做的實驗結果。
這裡寫圖片描述

下面,我們繼續分析方法View的onTouchEvent(MotionEvent 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;

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

首先看這個方法的說明,實現這個方法來處理觸控式螢幕幕的動作事件。如果這個方法被用來檢測點選動作,它是建議執行和呼叫的操作。如果這個事件被處理,返回true,否則返回false。
現在我們來看逐一程式碼,第一個if語句塊中,判斷View的狀態是否可用,如果不可用則設定為不可按壓,否則為設定為可點選和可長按。然後下面在可點選和可長按的條件下,進行touch事件的邏輯處理。在這個if語句內部有switch條件判斷,將分別對不同的事件進行處理,如MotionEvent.ACTION_UP,MotionEvent.ACTION_DOWN,MotionEvent.ACTION_CANCEL 和MotionEvent.ACTION_MOVE幾個不同的事件。下面我們將逐一對其進行分析。
首先是MotionEvent.ACTION_UP中:
判斷prepressed為true後,進入執行體;
設定setPressed(true, x, y);
判斷mHasPerformedLongPress是否執行長按操作,如果mOnLongClickListener.onLongClick 返回true時,mHasPerformedLongPress = true,這時便不會執行performClick()方法。否則繼續執行如下,判斷mPerformClick為空,初始化一個例項。新增到訊息佇列中,如果新增失敗則直接執行performClick()方法,否則在PerformClick物件的run中執行performClick()。檢視一下performClick()方法,如下:

  /**
     * Call this view's OnClickListener, if it is defined.  Performs all normal
     * actions associated with clicking: reporting accessibility event, playing
     * a sound, etc.
     *
     * @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) {
            playSoundEffect(SoundEffectConstants.CLICK);
            li.mOnClickListener.onClick(this);
            result = true;
        } else {
            result = false;
        }

        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
        return result;
    }

如上,我們可以看到一個非常熟悉的方法onClick。在if中判斷,如果我們給View設定了mOnClickListener的監聽介面,在這裡我們會回撥mOnClickListener中的onClick方法。(原來點選事件的onClick方法是在ACTION_UP時,執行的)
接著,看到建立UnsetPressedState物件,然後執行UnsetPressedState物件中的run方法,我們進入這個方法檢視,

  private final class UnsetPressedState implements Runnable {
        @Override
        public void run() {
            setPressed(false);
        }
    }

    /**
     * Sets the pressed state for this view.
     *
     * @see #isClickable()
     * @see #setClickable(boolean)
     *
     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
     *        the View's internal state from a previously set "pressed" state.
     */
    public void setPressed(boolean pressed) {
        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);

        if (pressed) {
            mPrivateFlags |= PFLAG_PRESSED;
        } else {
            mPrivateFlags &= ~PFLAG_PRESSED;
        }

        if (needsRefresh) {
            refreshDrawableState();
        }
        dispatchSetPressed(pressed);
    }

可以看到,這裡面是用來取消mPrivateFlags 中的PFLAG_PRESSED標誌,然後重新整理背景。
ACTION_UP最後一步,removeTapCallback() 移除訊息佇列中的之前加入的所有回撥操作。

接著分析MotionEvent.ACTION_DOWN中內部程式碼:
首先mHasPerformedLongPress = false,設定長按操作為false。
接著判斷View是否處在可滑動的容器中,如果為false,則設定View的PRESSED狀態和檢查長按動作。

接著分析MotionEvent.ACTION_CANCEL的事件:
程式碼非常簡單,設定PRESSED為false,移除所有的回撥,移除長按的回撥。

最後來分析MotionEvent.ACTION_MOVE的事件:
判斷觸控點是否移出View的範圍,如果移出了則執行removeTapCallback(),取消所有的回撥。接著判斷是否包含PRESSED標識,如果包含則執行方法removeLongPressCallback() 和 setPressed(false);

到這裡我們可以知道,onTouchEvent方法中處理Touch事件的具體操作,並控制了View的點選事件。在如果在點選View時,想要長按和短按都產生效果,即setOnLongClickListener和setOnClickListener都能夠執行的話,只需要在setOnLongClickListener的onLongClick方法中返回false,這時兩個方法便都能執行。
至此關於View的Touch事件分發流程已經分析完成,下一篇將介紹ViewGroup的分發機制。