Android事件分發機制

2021-07-25 22:19:19 字數 2824 閱讀 3549

花了一下午的事件研究了一下android的事件分發機制,覺得有必要總結一下

順便分享出來,希望對大家有用

1】首先最重要的是需要了解viewgroup裡面重寫的三個方法

1)dispatchtouchevent 用於事件的分發

2)onintercepttouchevent用於事件的攔截

3)ontouchevent用於事件的處理

2】android的事件分發是由上而下的,即從父類傳遞給子類,父view傳遞給子view

3】android的事件處理是由下而上的,即從子類傳遞給父類,子view傳遞給父view

理解上面三點之後,再來分別看一下這三個方法

我們只需要知道每乙個返回值對應的情況就能大致理解其作用了

1】dispatchtouchevent方法

1)return falas       

分為兩種情況:

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

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

2)return true     

事件會分發給當前 view 並由 dispatchtouchevent 方法進行消費,同時事件會停止向下傳遞

3) return super.dispatchtouchevent(ev)

事件會自動的分發給當前 view 的 onintercepttouchevent 方法

2】onintercepttouchevent方法

1)return false

事件會被當前view放行,將傳遞給子view的dispatchtouchevent方法

2)return true

事件被攔截,並且交給當前view的ontouchevent去處理

3)return super.onintercepttouchevent

事件會被當前view放行,將傳遞給子view的dispatchtouchevent方法

3】ontouchevent方法

1)return false

事件會被傳遞給activity或者父view的ontouchevent

處理,如果activity或者

父view的ontouchevent

也沒有處理,則事件消失

2)return true

事件會被攔截給當前view的ontouchevent

處理3)return super.ontouchevent

事件會被傳遞給activity或者父view的ontouchevent

處理,如果activity或者

父view的ontouchevent

也沒有處理,則事件消失

畫了一張圖,來解釋上面的文字描述

寫了乙個demo,可以自行更改每個方法的返回值來檢測log

下面貼上**,**很簡單

有乙個activity,乙個superview,childview,

toucheventutil用於列印日誌

activity:

public class mainactivity extends activity 

@override

public boolean dispatchtouchevent(motionevent event)

@override

public boolean ontouchevent(motionevent event)

}

superview:

public class superview extends

relativelayout

public superview(context context, attributeset attrs)

public superview(context context, attributeset attrs, int defstyleattr)

@override

public boolean

dispatchtouchevent(motionevent event)

@override

public boolean

onintercepttouchevent(motionevent event)

@override

public boolean

ontouchevent(motionevent event)

}

childview:

public class childview extends linearlayout 

public childview(context context, attributeset attrs)

public childview(context context, attributeset attrs, int defstyleattr)

@override

public boolean dispatchtouchevent(motionevent event)

@override

public boolean onintercepttouchevent(motionevent event)

@override

public boolean ontouchevent(motionevent event)

}

Android事件分發機制

public boolean dispatchtouchevent motionevent ev else return consume 上面的一段 將事件分發中三個主要方法的關係表現。一 touch 事件分析 事件分發 public boolean dispatchtouchevent motio...

Android事件分發機制

一 三個重要的方法 dispatchtouchevent onintercepttouchevent activity和view無此方法 activity 作為事件的原始分發著會造成無響應 view最為事件的最末端要麼處理事件,要麼回傳事件 ontouchevent 二 事件分發流程 activit...

Android事件分發機制

android的事件傳遞對應著三個階段 分發 攔截和消費,分發 對應的方法是dispatchtouchevent方法,在android系統中,所有的觸控事件都是通過這個方法來分發的。返回值為true表示事件被當前檢視消費掉,返回super.方法表示繼續分發該事件,如果當前檢視是viewgroup及其...