Android事件分發

2021-07-22 13:52:50 字數 2259 閱讀 4267

android 中與 touch 事件相關的方法包括:dispatchtouchevent(motionevent ev)、onintercepttouchevent(motionevent ev)、ontouchevent(motionevent ev);能夠響應這些方法的控制項包括:viewgroup 及其子類、activity。方法與控制項的對應關係如下表所示:

touch 事件相關方法

方法功能 

viewgroup  

activity    

public boolean dispatchtouchevent(motionevent ev)

事件分發

yesyes

public boolean onintercepttouchevent(motionevent ev) 

事件攔截

yesno

public boolean ontouchevent(motionevent ev)

事件響應

yesyes

從這張表中我們可以看到 viewgroup 及其子類對與 touch 事件相關的三個方法均能響應,而 activity 對 onintercepttouchevent(motionevent ev)

也就是事件攔截不進行響應。另外需要注意的是 view 對 dispatchtouchevent(motionevent ev)

和 onintercepttouchevent(motionevent ev)

的響應的前提是可以向該 view 中新增子 view,如果當前的 view 已經是乙個最小的單元 view(比如 textview),那麼就無法向這個最小 view 中新增子 view,也就無法向子 view 進行事件的分發和攔截,所以它沒有 dispatchtouchevent(motionevent ev)

和 onintercepttouchevent(motionevent ev)

,只有 ontouchevent(motionevent ev)

一、touch 事件分析

事件分發:public boolean dispatchtouchevent(motionevent ev)

touch 事件發生時

activity 的 dispatchtouchevent(motionevent ev) 方法會以隧道方式(從根元素依次往下傳遞直到最內層子元素或在中間某一元素中由於某一條件停止傳遞)

將事件傳遞給最外層 view 的 dispatchtouchevent(motionevent ev) 方法,並由該 view 的 dispatchtouchevent(motionevent ev) 方法對事件進行分發。dispatchtouchevent 的事件分發邏輯如下:

如果當前 view 獲取的事件直接來自 activity,則會將事件返回給 activity 的 ontouchevent 進行消費;

如果當前 view 獲取的事件來自外層父控制項,則會將事件返回給父 view 的  ontouchevent 進行消費。

事件攔截:public boolean onintercepttouchevent(motionevent ev)

在外層 view 的 dispatchtouchevent(motionevent ev) 方法返回系統預設的 super.dispatchtouchevent(ev) 情況下,事件會自動的分發給當前 view 的 onintercepttouchevent 方法。onintercepttouchevent

的事件攔截邏輯如下:

事件響應:public boolean ontouchevent(motionevent ev)

在 dispatchtouchevent 返回 super.dispatchtouchevent(ev) 並且 onintercepttouchevent 返回 true 或返回 super.onintercepttouchevent(ev) 的情況下 ontouchevent 會被呼叫。ontouchevent 的事件響應邏輯如下:

到這裡,與 touch 事件相關的三個方法就分析完畢了。下面的內容會通過各種不同的的測試案例來驗證上文中三個方法對事件的處理邏輯。

Android 事件分發

touch 事件的分發和消費機制dispatchtouchevent onintercepttouchevent 和ontouchevent dispatchtouchevent 事件分發 true 事件會分發給當前view 並由dispatchtouchevent 方法消費,同時停止向下傳 fal...

Android事件分發

當使用者觸控螢幕時,系統會對觸控事件做出相應的相應,這個事件會產生乙個motionevent,系統根據一定的規則將其傳遞給view進行處理,這個過程就是事件分發機制了。事件的傳遞分為兩個階段,即捕獲階段和冒泡階段。捕獲階段 事件最先由最外層的view接收,然後依次向內層傳遞,直到傳遞到最小的view...

Android 事件分發

案例說明 linearlayout 下面有3個recyclerview 當手指在螢幕的中間上半屏滑動的時候,3個recyclerview會一起滑動 當手指在螢幕的下半屏滑動的餓時候,各自區域的recyclerview單獨滑動 先看下 效果圖 需要重寫linearlayout public class...