1. 程式人生 > >android的事件分發機制

android的事件分發機制

我們在面試的時候經常會被問到android事件分發機制,對於這個知識點其實也不算太難,關鍵在於不好理解,其實總結下來就兩句話:
android事件分發過程:先由父類控制元件判斷是否攔截(onInterceptTouchEvent() is true or false),攔截的話則執行該View的onTouchEvent()事件,否則則繼續分發...
android事件處理過程:由子View先處理,如果子View不處理則交由父控制元件處理,否則一直向上傳遞。
舉個例子:
這裡有3個控制元件,分別實現了dispatchTouchEvent(),onInterceptTouchEvent(),onTouchEvent();
<?xml version="1.0" encoding="utf-8"?>
<com.luck.anim.touch.MyLinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

    <com.luck.anim.touch.MyRelativeLayout
android
:layout_width="match_parent" android:layout_height="match_parent"> <com.luck.anim.touch.MyButton android:id="@+id/my_btn" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="自定義Button" /> </com.luck.anim.touch.MyRelativeLayout> </com.luck.anim.touch.MyLinearLayout
>
當我們都按預設返回的話,我點選MyButton時,執行的順序是:
MyLinearLayout--->: dispatchTouchEvent
MyLinearLayout--->: onInterceptTouchEvent
MyRelativeLayout--->: dispatchTouchEvent
MyRelativeLayout--->: onInterceptTouchEvent
MyButton--->: dispatchTouchEvent
MyButton--->: onTouchEvent
但我們在MyRelativeLayout中攔截此事件的話他的一個分發過程又是如何的呢?
MyLinearLayout--->: dispatchTouchEvent
MyLinearLayout--->: onInterceptTouchEvent
MyRelativeLayout--->: dispatchTouchEvent
MyRelativeLayout--->: onInterceptTouchEvent
MyRelativeLayout--->: onTouchEvent
MyLinearLayout--->: onTouchEvent
從這裡可以看出當我們在某一層View中攔截掉事件的話,他不會繼續向下分發了,而是執行自身View的3個函數了,但當我們並沒有在當前View的onTouchEvent()事件做處理時,他還同時向上父級執行了onTouchEvent()事件。