對View組件touch事件響應的理解

來源:互聯網
上載者:User

    Android響應View組件的touch事件通常是採用重寫onTouch(MotionEvent event)方法,或者是setOnTouchListener()設定listener.View組件的touch事件的響應是通過調用dispatchTouchEvent(MotionEvent event)方法分發的,當touch listener為null或者它返回的結果是false時,就調用onTouch()方法,所以touch listener的優先順序要比onTouch()方法的高。當onTouch()方法返回false時,才會觸發view組件parent的touch事件響應。

    ViewGroup的dispatchTouchEvent()方法有所不同,它會對touch事件進行解析,通過調用onInterceptTouchEvent(MotionEvent event), 若返回false時會將事件分發給響應的子組件,否則自己響應這個touch事件,預設的為false, 可以對這個方法進行重寫來攔截touch事件。因此,view組件響應事件的機制是,touch事件從view組件樹頂層一直分發下去到最底層的組件上,當組件沒有consume這個事件時會傳回到上一級進行處理,直到返回到最底層扔出,這會最終被Activity進行處理,因為事件最開始分發的地方是從Activity開始的,它會調用getWindow().superDispatchTouchEvent(ev)方法把事件分發給組件樹,若果view組件樹沒有處理則最終會調用自己的onTouch(MotionEvent event)方法。

聯繫我們

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