Android View 事件分發機制梳理

來源:互聯網
上載者:User

標籤:

View初探

一直以來對View的事件分發機制很暈,今天就在這裡梳理一下

MyView

首先繼承View類,自訂一個MyView。並在初始化時列印View類是否可點擊,這裡從View點擊事件分發的角度出發,所以不考慮繪製,測量相關方法的實現。

    public class MyView extends View {    String TAG = "Activity";    public MyView(Context context) {        super(context);        init();    }    public MyView(Context context, AttributeSet attrs) {        super(context, attrs);        init();    }    public MyView(Context context, AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);        init();    }    private void init() {        Log.e(TAG, "the View clickable is " + isClickable());    }}

將整個MyView放置到布局檔案中,看Log日誌。

    <engineer.test.MyView        android:id="@+id/myview"        android:layout_width="150dp"        android:layout_height="150dp"        android:layout_centerInParent="true"        android:background="#ff00ff" />

可以看到,View類預設是不可點擊的。

監聽View的Touch事件

這裡首先明確MotionEvent中事件所對應的值

    public static final int ACTION_DOWN= 0;    public static final int ACTION_UP= 1;    public static final int ACTION_MOVE= 2

給MyView設定OnTouchListener,並列印事件記錄

    myView = (MyView) findViewById(R.id.myview);    myView.setOnTouchListener(new View.OnTouchListener() {            @Override            public boolean onTouch(View v, MotionEvent event) {                Log.e(TAG, "myview_onTouch---->"+event.getAction());                return false;            }        });

點擊一下MyView看日誌:

可以看到,這裡只有ACTION_DOWN事件發生,ACTION_UP事件並沒有發生,這是為什嗎?

給MyView設定OnClickListener,並列印日誌

myView.setOnClickListener(new View.OnClickListener() {        @Override        public void onClick(View v) {            Log.e(TAG, "the View clickable is " + myView.isClickable());            Log.e(TAG, "myview_onClick");        }    });

點擊一下MyView看日誌:

可以看到,設定ClickListener之後:

  • MyView直接由一個不可點擊的控制項變成了可點擊控制項,isClickable返回true。
  • ACTION_DOWN和ACTION_UP事件都發生了。
  • Touch事件先於Click事件發生。

我們看到TouchListener的onTouch方法是有傳回值的,而且預設返回為false,我們將其改為true,然後點擊MyView看日誌:

可以看到,多次點擊MyView後,Click方法沒有執行,即onTouch事件返回true時,相當於屏蔽了click事件的發生

View源碼分析

根據上面所獲得的一系列結果和疑問,我們去看看View中關於事件分發的兩個方法dispatchTouchEvent和onTouchEvent。

首先看dispatchTouchEvent,因為首先執行的也是這個方法

API 注釋

/**
* 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.
*/

從注釋可以看到,這個方法返回true就是當前view要處理此次事件。

dispatchTouchEvent源碼(截取主要內容)
 public boolean dispatchTouchEvent(MotionEvent event) {              boolean result = false;                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;            }        }        return result;    }

可以看到,這裡預設的傳回值預設是result=false

  • 首先,onFilterTouchEventForSecurity方法檢測,點擊事件是否確實發生在當前view上,如果是的話,view就會處理當前點擊事件,否則的話就直接返回false不去處理此次事件。
  • 接著,當view的touchListener不為null,且View是enable,並且touchListener的onTouch方法返回true時,result=true,這樣下面的if語句中onTouchEvent方法就不會執行,這樣onClick方法就不會調用了,這也和之前最後一種測試的結果是一致的。

但是正常情況下,onTouch方法是返回false的,所以就會執行到下面onTouchEvent方法中去了。

onTouchEvent源碼(截取主要邏輯)
 public boolean onTouchEvent(MotionEvent event) {        final float x = event.getX();        final float y = event.getY();        final int viewFlags = mViewFlags;        final int action = event.getAction();        //view不是enable時,也會消耗touch事件,只是就此返回,不會進入到performClick()方法中        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();                        }                            // 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();                                }                            }                    }                    break;            }            //switch完畢後,最終會返回true            return true;        }        //如果click,longclick以及contextClickable都為false時,返回false        return false;    }

可以看到,一個正常的veiw(即enable時),且可以點擊時,在ACTION_UP的時候,最終會進入performclick()這個方法中去

可以再看一下,performanceclick方法的實現

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

最終會執行onClickListener中的onClick方法,也就是平常我們去實現的那個方法。

同時,也可以看到可以clickable,longclickable以及contextclickable中只要有一個為true,那麼在switch最後也會返回true,這樣返回到上面的dispatchTouchEvent方法,返回result也為true,即完整的消耗(處理)了此次touch事件

這裡可以自己去看一下完整的源碼,整體結構上就是一旦進入if語句內部,switch執行完畢後,return true,即確保能夠完全處理此次touch事件。

當然,如果clickable,longclickable以及contextclickable這三個都為false時,就不會進入if語句,直接返回為false,dispatchTouchEvent方法的返回也為false,即表示沒有處理此次touch事件,這種情況就是一開始,我們只為MyView設定onTouchListener而沒有設定onClickListener時的發生情況,View類預設不可點擊,那麼當我們點擊MyView時,ACTION_DOWN執行,onTouch()方法返回false,接著onTouchEvent也返回false,這樣後續事件就不會繼續執行了,所以也就不會有ACTION_UP了

好了,這樣終於理清了View(不包括ViewGroup)的touch事件分發機制。

最終得出下面結論:

View接收到Touch事件時各個方法執行順序

onTouch–>onTouchEvent–>onClick

onTouch預設返回false,返回true時後續事件無法執行

dispatchTouchEvent返回true表示處理了touch事件,返回結果受onTouchEvent方法影響

onTouchEvent返回true表示已消耗touch事件,否則的話不消耗。

view enable屬性的true和false,不能完全決定touch事件的傳遞,還得考慮其listener

疑惑:這裡源碼中CONTEXT_CLICKABLE這個屬性實在是沒能理解,網上也沒找到解釋。

Android View 事件分發機制梳理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.