標籤:
學習網址:http://www.apkbus.com/forum.php?mod=viewthread&tid=44296
1:Android Touch事件傳遞機制解析android系統中的每個View的子類都具有下面三個和TouchEvent處理密切相關的方法:1)public boolean dispatchTouchEvent(MotionEvent ev) 分發TouchEvent2)public boolean onInterceptTouchEvent(MotionEvent ev) 攔截TouchEvent3)public boolean onTouchEvent(MotionEvent ev) 處理TouchEvent
2、傳遞流程
(1) 事件從Activity.dispatchTouchEvent()開始傳遞,只要沒有被停止或攔截,從最上層的View(ViewGroup)開始一直往下(子View)傳遞。子View可以通過onTouchEvent()對事件進行處理。
(2) 事件由父View(ViewGroup)傳遞給子View,ViewGroup可以通過onInterceptTouchEvent()對事件做攔截,停止其往下傳遞。
(3) 如果事件從上往下傳遞過程中一直沒有被停止,且最底層子View沒有消費事件,事件會反嚮往上傳遞,這時父View(ViewGroup)可以進行消費,如果還是沒有被消費的話,最後會到Activity的onTouchEvent()函數。
(4) 如果View沒有對ACTION_DOWN進行消費,之後的其他事件不會傳遞過來。
(5) OnTouchListener優先於onTouchEvent()對事件進行消費。
上面的消費即表示相應函數傳回值為true。
下面看個執行個體:定義了2種狀態
狀態1:由center處理Touch事件
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <dk.touch.MyLayout android:id="@+id/out" android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="center" android:background="#ff345600" > <dk.touch.MyLayout android:id="@+id/middle" android:layout_width="200dp" android:layout_height="200dp" android:gravity="center" android:background="#ff885678" > <dk.touch.MyLayout android:id="@+id/center" android:layout_width="50dp" android:layout_height="50dp" android:background="#ff345678" android:focusable="true" android:focusableInTouchMode="true" android:clickable="true" > </dk.touch.MyLayout> </dk.touch.MyLayout> </dk.touch.MyLayout></LinearLayout>
處理機制:
狀態2:都不處理事件
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <dk.touch.MyLayout android:id="@+id/out" android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="center" android:background="#ff345600" > <dk.touch.MyLayout android:id="@+id/middle" android:layout_width="200dp" android:layout_height="200dp" android:gravity="center" android:background="#ff885678" > <dk.touch.MyLayout android:id="@+id/center" android:layout_width="50dp" android:layout_height="50dp" android:background="#ff345678" > </dk.touch.MyLayout> </dk.touch.MyLayout> </dk.touch.MyLayout></LinearLayout>
處理機制:
繼續學習中
android touchEvent事件學習