Android事件傳遞機制【Touch事件】

來源:互聯網
上載者:User

 

Android中提供了ViewGroup、View、Activity三個等級的Touch事件處理。也就是說,這三個地方都有事件回調方法。

 

測試DEMO視圖結構:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<com .orgcent.eventtest.EventLinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:background="#032d3d"
   android:orientation="vertical" >
    <com .orgcent.eventtest.EventTextView
       android:id="@+id/tvEvent"
       android:layout_width="fill_parent"
       android:layout_height="100dp"
       android:gravity="center"
       android:textColor="@android:color/black"
       android:background="@android:color/white"
       android:text="Activity - ViewGroup - View Event http://orgcent.com dispatch Test"/>
</com>

 

至於三者之間的執行順序,將在下面詳細闡述:

 

整體上看,事件行程順序為ViewGroup::onInterceptTouchEvent() –> ViewGroup或View的onTouchEvent() –> Activity::onTouchEvent()

由於上面每個事件回調方法的傳回值不同,導致事件本身及順序發生微妙變化。下面以傳回值為主線來詳細闡述:

 

需要注意以下兩點:
1、onInterceptTouchEvent()返回true,那麼這個方法只會攔截動作ACTION_DOWN。
2、onInterceptTouchEvent()負責事件分發(事件傳遞方向),onTouchEvent()負責事件處理(消費)。

 

1、ViewGroup的onInterceptTouchEvent()
返回false:
預設實現方式。事件(按下、移動、抬起等)將直接傳遞給目標view(使用者觸摸的view)。
在ViewGroup觸發,調用ViewGroup::onTouchEvent(),在View觸發,調用View::onTouchEvent()。

 


PS:這裡發現ViewGroup::onTouchEvent()也被調用了,原因是View::onTouchEvent()沒有處理該事件(返回false),事件將交給父容器處理。

 

返回true:
表示ViewGroup將攔截子View的Touch事件。事件會直接傳遞到ViewGroup::onTouchEvent()處理。
也就是說,事件後面的移動、抬起動作不會經過onInterceptTouchEvent(),而是直接傳到onTouchEvent()。

 

 

2、ViewGroup/View的onTouchEvent()
返回true:
表示事件按下動作被處理,意味著事件的移動、抬起等後續動作將會傳到此方法。
如果是View處理,那麼ViewGroup的onTouchEvent()將不會獲得該事件。

 


PS:只要onInterceptTouchEvent()返回false,而且目標控制項View::onTouchEvent()返回true,那麼事件的每一個動作(按下、移動、抬起等)會都會首先傳遞到onInterceptTouchEvent()中。

 

如果是ViewGroup處理,那麼Activity不會獲得事件。

 

返回false:
表示View或ViewGroup不處理事件,系統將把事件傳遞給其父級處理。

 

如果View返回false,那麼將由其父容器ViewGroup處理。如果ViewGroup不處理,最終將交給Activity來處理。

 

如果ViewGroup返回false,將交給最後一級Activity來處理。

 

3、Activity的onTouchEvent()
這個方法是事件最後被處理的地方。如果不處理,系統將拋棄這個事件。暫時沒有發現這個方法的傳回值對程式有什麼意義。也許返回true能告訴系統事件被處理了。

 

小提示:
不要直接在程式中呼叫事件的回調方法。可以使用dispatchTouchEvent(MotionEvent)來分發事件。

 

DEMO:android_event_test.zip (56.8 KB, 47 次)

 

轉載請註明地址: http://orgcent.com/android-touch-event-mechanism/ | 蘿蔔白菜的部落格

 


 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.