Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android 源碼解析View的touch事件分發機制

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

編輯:關於Android編程

概述

本篇主要分析的是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布局中引用該控件,非常簡單。



    

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

接著我們恢復之前的返回值false,繼續讓mybutton設置一個setOnTouchListener監聽事件,關鍵代碼如下:<喎?/kf/ware/vc/" target="_blank" class="keylink">vcD4NCjxwcmUgY2xhc3M9"brush:java;"> 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.
     *
     * 

Calling this method when a nested scroll is not currently in progress is harmless.

* * @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 mOnLayoutChangeListeners;

        /**
         * Listeners for attach events.
         */
        private CopyOnWriteArrayList 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;
    }
1

首先看這個方法的說明,實現這個方法來處理觸摸屏幕的動作事件。如果這個方法被用來檢測點擊動作,它是建議執行和調用的操作。如果這個事件被處理,返回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的分發機制。

  • obeying click sound preferences *
  • dispatching OnClickListener calls *
  • handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when * accessibility features are enabled *
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved