參考資料:
1. 基礎認知
(1)事件分發的對象是什麼?
答:Touch事件; 包括點擊,長按,滑動等相關事件;比如ACTION_DOWN
或ACTION_MOVE
或ACTION_UP
;
(2)事件分發的本質是什麼?
答:事件傳遞的過程;
(3)事件分發(傳遞)的順序?事件消費(處理)的順序 ?
- 事件分發順序:
Activity
->(PhoneWindow
->DecorView
-> )ViewGroup
->View
(從外到內); - 事件消費順序:
View
->ViewGroup
->(DecorView
->PhoneWindow
) ->Activity
(從內到外);
2. 源碼分析
2.1 Activity 事件分發
當一個點擊事件發生時,事件最先傳到Activity
的dispatchTouchEvent()
進行事件分發;
//源碼分析:Activity.dispatchTouchEvent()
public boolean dispatchTouchEvent(MotionEvent ev) {
// 一般事件列開始都是DOWN事件 = 按下事件,故此處基本是true
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
onUserInteraction();//僅瞭解,實現屏保功能
}
// ->>分析2
if (getWindow().superDispatchTouchEvent(ev)){
return true;
// 若getWindow().superDispatchTouchEvent(ev)的返回true
// 則Activity.dispatchTouchEvent()就返回true,則方法結束。即 :該點擊事件停止往下傳遞 & 事件傳遞過程結束
// 否則:繼續往下調用Activity.onTouchEvent
}
// ->>分析4
return onTouchEvent(ev);
}
/**
* 分析2:getWindow().superDispatchTouchEvent(ev)
* 說明:
* a. getWindow() = 獲取Window類的對象
* b. Window類是抽象類,其唯一實現類 = PhoneWindow類;即此處的Window類對象 = PhoneWindow類對象
* c. Window類的superDispatchTouchEvent() = 1個抽象方法,由子類PhoneWindow類實現
*/
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
return mDecor.superDispatchTouchEvent(event);
// mDecor = 頂層View(DecorView)的實例對象
// ->> 分析3
}
/**
* 分析3:mDecor.superDispatchTouchEvent(event)
* 定義:屬於頂層View(DecorView)
* 說明:
* a. DecorView類是PhoneWindow類的一個內部類
* b. DecorView繼承自FrameLayout,是所有界面的父類
* c. FrameLayout是ViewGroup的子類,故DecorView的間接父類 = ViewGroup
*/
public boolean superDispatchTouchEvent(MotionEvent event) {
return super.dispatchTouchEvent(event);
// 調用父類的方法 = ViewGroup的dispatchTouchEvent()
// 即 將事件傳遞到ViewGroup去處理,詳細請看ViewGroup的事件分發機制
}
// 回到最初的調用原處
/**
* 分析4:Activity.onTouchEvent()
* 當事件未被下級View消費時
*/
public boolean onTouchEvent(MotionEvent event) {
// ->> 分析5
if (mWindow.shouldCloseOnTouch(this, event)) {
finish();
return true;//點擊事件發生在Window邊界外
}
return false;//點擊事件發生在Window邊界內
}
2.2 ViewGroup 事件分發
/**
* 源碼分析:ViewGroup.dispatchTouchEvent()
*/
public boolean dispatchTouchEvent(MotionEvent ev) {
... // 僅貼出關鍵代碼
// 重點分析1:ViewGroup每次事件分發時,都需調用onInterceptTouchEvent()詢問是否攔截事件
if (disallowIntercept || !onInterceptTouchEvent(ev)) {
// 判斷值1:disallowIntercept = 是否禁用事件攔截的功能(默認是false),可通過調用requestDisallowInterceptTouchEvent()修改
// 判斷值2: !onInterceptTouchEvent(ev) = 對onInterceptTouchEvent()返回值取反
// a. 若在onInterceptTouchEvent()中返回false(即不攔截事件),就會讓第二個值爲true,從而進入到條件判斷的內部
// b. 若在onInterceptTouchEvent()中返回true(即攔截事件),就會讓第二個值爲false,從而跳出了這個條件判斷
// c. 關於onInterceptTouchEvent() ->>分析1
ev.setAction(MotionEvent.ACTION_DOWN);
final int scrolledXInt = (int) scrolledXFloat;
final int scrolledYInt = (int) scrolledYFloat;
final View[] children = mChildren;
final int count = mChildrenCount;
// 重點分析2
// 通過for循環,遍歷了當前ViewGroup下的所有子View
for (int i = count - 1; i >= 0; i--) {
final View child = children[i];
if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE
|| child.getAnimation() != null) {
child.getHitRect(frame);
// 判斷當前遍歷的View是不是正在點擊的View,從而找到當前被點擊的View
// 若是,則進入條件判斷內部
if (frame.contains(scrolledXInt, scrolledYInt)) {
final float xc = scrolledXFloat - child.mLeft;
final float yc = scrolledYFloat - child.mTop;
ev.setLocation(xc, yc);
child.mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
// 條件判斷的內部調用了該View的dispatchTouchEvent()
// 即 實現了點擊事件從ViewGroup到子View的傳遞(具體請看下面的View事件分發機制)
if (child.dispatchTouchEvent(ev)) {
mMotionTarget = child;
return true;
// 調用子View的dispatchTouchEvent後是有返回值的
// 若該控件可點擊,那麼點擊時,dispatchTouchEvent的返回值必定是true,因此會導致條件判斷成立
// 於是給ViewGroup的dispatchTouchEvent()直接返回了true,即直接跳出
// 即把ViewGroup的點擊事件攔截掉
}
}
}
}
}
}
boolean isUpOrCancel = (action == MotionEvent.ACTION_UP) ||
(action == MotionEvent.ACTION_CANCEL);
if (isUpOrCancel) {
mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;
}
final View target = mMotionTarget;
// 重點分析3
// 若點擊的是空白處(即無任何View接收事件) / 攔截事件(手動複寫onInterceptTouchEvent(),從而讓其返回true)
if (target == null) {
ev.setLocation(xf, yf);
if ((mPrivateFlags & CANCEL_NEXT_UP_EVENT) != 0) {
ev.setAction(MotionEvent.ACTION_CANCEL);
mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
}
return super.dispatchTouchEvent(ev);
// 調用ViewGroup父類的dispatchTouchEvent(),即View.dispatchTouchEvent()
// 因此會執行ViewGroup的onTouch() ->> onTouchEvent() ->> performClick() ->> onClick(),即自己處理該事件,事件不會往下傳遞(具體請參考View事件的分發機制中的View.dispatchTouchEvent())
// 此處需與上面區別:子View的dispatchTouchEvent()
}
...
}
/**
* 分析1:ViewGroup.onInterceptTouchEvent()
* 作用:是否攔截事件
* 說明:
* a. 返回true = 攔截,即事件停止往下傳遞(需手動設置,即複寫onInterceptTouchEvent(),從而讓其返回true)
* b. 返回false = 不攔截(默認)
*/
public boolean onInterceptTouchEvent(MotionEvent ev) {
return false;
}
// 回到調用原處
2.3 View 事件分發
/**
* 源碼分析:View.dispatchTouchEvent()
*/
public boolean dispatchTouchEvent(MotionEvent event) {
if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED &&
mOnTouchListener.onTouch(this, event)) {
return true;
}
return onTouchEvent(event);
}
// 說明:只有以下3個條件都爲真,dispatchTouchEvent()才返回true;否則執行onTouchEvent()
// 1. mOnTouchListener != null
// 2. (mViewFlags & ENABLED_MASK) == ENABLED
// 3. mOnTouchListener.onTouch(this, event)
// 下面對這3個條件逐個分析
/**
* 條件1:mOnTouchListener != null
* 說明:mOnTouchListener變量在View.setOnTouchListener()方法裏賦值
*/
public void setOnTouchListener(OnTouchListener l) {
mOnTouchListener = l;
// 即只要我們給控件註冊了Touch事件,mOnTouchListener就一定被賦值(不爲空)
}
/**
* 條件2:(mViewFlags & ENABLED_MASK) == ENABLED
* 說明:
* a. 該條件是判斷當前點擊的控件是否enable
* b. 由於很多View默認enable,故該條件恆定爲true
*/
/**
* 條件3:mOnTouchListener.onTouch(this, event)
* 說明:即 回調控件註冊Touch事件時的onTouch();需手動複寫設置,具體如下(以按鈕Button爲例)
*/
button.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return false;
}
});
// 若在onTouch()返回true,就會讓上述三個條件全部成立,從而使得View.dispatchTouchEvent()直接返回true,事件分發結束
// 若在onTouch()返回false,就會使得上述三個條件不全部成立,從而使得View.dispatchTouchEvent()中跳出If,執行onTouchEvent(event)
/ *
* 源碼分析:View.onTouchEvent()
*/
public boolean onTouchEvent(MotionEvent event) {
final int viewFlags = mViewFlags;
if ((viewFlags & ENABLED_MASK) == DISABLED) {
return (((viewFlags & CLICKABLE) == CLICKABLE ||
(viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
}
if (mTouchDelegate != null) {
if (mTouchDelegate.onTouchEvent(event)) {
return true;
}
}
// 若該控件可點擊,則進入switch判斷中
if (((viewFlags & CLICKABLE) == CLICKABLE ||
(viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
switch (event.getAction()) {
// a. 若當前的事件 = 擡起View(主要分析)
case MotionEvent.ACTION_UP:
boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
...// 經過種種判斷,此處省略
// 執行performClick() ->>分析1
performClick();
break;
// b. 若當前的事件 = 按下View
case MotionEvent.ACTION_DOWN:
if (mPendingCheckForTap == null) {
mPendingCheckForTap = new CheckForTap();
}
mPrivateFlags |= PREPRESSED;
mHasPerformedLongPress = false;
postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
break;
// c. 若當前的事件 = 結束事件(非人爲原因)
case MotionEvent.ACTION_CANCEL:
mPrivateFlags &= ~PRESSED;
refreshDrawableState();
removeTapCallback();
break;
// d. 若當前的事件 = 滑動View
case MotionEvent.ACTION_MOVE:
final int x = (int) event.getX();
final int y = (int) event.getY();
int slop = mTouchSlop;
if ((x < 0 - slop) || (x >= getWidth() + slop) ||
(y < 0 - slop) || (y >= getHeight() + slop)) {
// Outside button
removeTapCallback();
if ((mPrivateFlags & PRESSED) != 0) {
// Remove any future long press/tap checks
removeLongPressCallback();
// Need to switch from pressed to not pressed
mPrivateFlags &= ~PRESSED;
refreshDrawableState();
}
}
break;
}
// 若該控件可點擊,就一定返回true
return true;
}
// 若該控件不可點擊,就一定返回false
return false;
}
/**
* 分析1:performClick()
*/
public boolean performClick() {
if (mOnClickListener != null) {
playSoundEffect(SoundEffectConstants.CLICK);
mOnClickListener.onClick(this);
return true;
// 只要我們通過setOnClickListener()爲控件View註冊1個點擊事件
// 那麼就會給mOnClickListener變量賦值(即不爲空)
// 則會往下回調onClick() & performClick()返回true
}
return false;
}
onTouch()
、onTouchEvent()
和onClick()
的關係?
- onTouch返回true ,dispatchTouchEvent直接返回true;
- onTouch返回false -> onTouchEvent -> performClick -> onClick();
- 涉及到倆個監聽器:OnTouchListener(抽象)和OnClickListener(具體)
3 三個回調方法
三個回調方法關係的僞碼(也是Activity、ViewGroup、View事件分發機制源碼的簡化版源碼)
boolean dispatchTouchEvent(MotionEvent event){
if(this instanceof View ){
if(mOnTouchListener.onTouch(this, event))
return ture;
return onTouchEvent(event); //View的dispatchTouchEvent返回值和onTouchEvent一致
}else if(this instanceof ViewGroup ){
//ViewGroup和Activity的dispatchTouchEvent返回值取決於下級View的dispatchTouchEvent方法和當前View的onTouchEvent方法
if(!onInterceptTouchEvent(event)){
if (child.dispatchTouchEvent(event))
return true;
}
return onTouchEvent(event);
} else if(this instanceof Activity ){
if (child.dispatchTouchEvent(event))
return true;
return onTouchEvent(event);
}
}
4 事件分發機制 流程圖
(1)理解事件分發機制的一個通俗例子:
有個公司有總經理、項目經理、程序員三人;甲方把項目先交給總經理,然後總經理把項目交給項目經理,項目經理把項目交給程序員處理(事件分發)。如果程序員能完成這個項目,在完成項目後就向項目經理報告,項目經理向總經理報告,總經理向甲方報告(dispatchTouchEvent逐層向上返回true)。如果程序員不能完成這個項目,就把這個項目交給上級項目經理處理,經理處理如果也完成不了,就交給總經理處理,總經理自己無論能否完成都需要向甲方報告。(事件消費)
(2)事件分發機制的一些結論:
- 一般一個事件序列只被一個View消費;
- 當onInterceptTouchEvent()方法返回一個true,不再被調用;
- 一個View一旦開始處理事件,如果它不消費ACTION_DOWN事件(onTouchEvent返回false),後續事件都不會分發給該View處理,並將事件重新交給它的父元素處理,即父元素的onTouchEvent會被調用;
- 只有ViewGroup有onIntercept()方法,View沒有;
- 只要View的clickable或longClickable有一個爲true,View的onTouchEvent默認消費(返回true);
5 .舉例
ViewGroupA.java
public class ViewGroupA extends LinearLayout {
public ViewGroupA(Context context) {
super(context);
}
public ViewGroupA(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public ViewGroupA(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
Log.d("DavidHuang------>","ViewGroupA # dispatchTouchEvent");
return super.dispatchTouchEvent(ev);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
Log.d("DavidHuang------>","ViewGroupA # onInterceptTouchEvent");
return super.onInterceptTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
Log.d("DavidHuang------>","ViewGroupA # onTouchEvent");
return super.onTouchEvent(event);
}
}
ViewGroupB.java
public class ViewGroupB extends LinearLayout {
public ViewGroupB(Context context) {
super(context);
}
public ViewGroupB(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public ViewGroupB(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
Log.d("DavidHuang------>","ViewGroupB # dispatchTouchEvent");
return super.dispatchTouchEvent(ev);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
Log.d("DavidHuang------>","ViewGroupB # onInterceptTouchEvent");
return super.onInterceptTouchEvent(ev);
// return true;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
Log.d("DavidHuang------>","ViewGroupB # onTouchEvent");
// return true;
return super.onTouchEvent(event);
}
}
ViewC.java
public class ViewC extends View {
public ViewC(Context context) {
super(context);
}
public ViewC(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public ViewC(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
Log.d("DavidHuang------>","ViewC # dispatchTouchEvent");
return super.dispatchTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
Log.d("DavidHuang------>","ViewC # onTouchEvent");
// return false;
return super.onTouchEvent(event);
}
activity_main.java
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/my_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusableInTouchMode="true"
android:orientation="vertical">
<com.example.davidhuang.dispatchtouchevent.ViewGroupA
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:background="#ff0033">
<com.example.davidhuang.dispatchtouchevent.ViewGroupB
android:layout_width="200dp"
android:layout_height="200dp"
android:gravity="center"
android:background="#336699">
<com.example.davidhuang.dispatchtouchevent.ViewC
android:layout_width="100dp"
android:layout_height="100dp"
android:clickable="true"
android:background="#ffff00"/>
</com.example.davidhuang.dispatchtouchevent.ViewGroupB>
</com.example.davidhuang.dispatchtouchevent.ViewGroupA>
</LinearLayout>
(1) 默認情況
//ACTION_DOWN
ViewGroupA # dispatchTouchEvent
ViewGroupA # onInterceptTouchEvent
ViewGroupB # dispatchTouchEvent
ViewGroupB # onInterceptTouchEvent
ViewC # dispatchTouchEvent
ViewC # onTouchEvent
//ACTION_UP
ViewGroupA # dispatchTouchEvent
ViewGroupA # onInterceptTouchEvent
ViewGroupB # dispatchTouchEvent
ViewGroupB # onInterceptTouchEvent
ViewC # dispatchTouchEvent
ViewC # onTouchEvent
ACTION_DOWN事件從ViewGroupA傳遞到ViewC,ViewC消費了這個事件;後續事件也交給ViewC處理;
(2)ViewC不處理
修改ViewC代碼如下:
@Override
public boolean onTouchEvent(MotionEvent event) {
Log.d("DavidHuang------>","ViewC # onTouchEvent");
return false;
// return super.onTouchEvent(event);
}
//ACTION_DOWN
ViewGroupA # dispatchTouchEvent
ViewGroupA # onInterceptTouchEvent
ViewGroupB # dispatchTouchEvent
ViewGroupB # onInterceptTouchEvent
ViewC # dispatchTouchEvent
ViewC # onTouchEvent
ViewGroupB # onTouchEvent
ViewGroupA # onTouchEvent
既然ViewC不處理事件,事件向上交付給上級ViewGroupB處理;ViewGroupB默認是不處理事件的,又交給ViewGroupB的上級ViewGroupA處理;ViewGroupA默認也不處理,交給Activity處理。
既然ABC都不處理ACTION_DOWN事件,所以後續事件不會被ABC接收,故沒有任何輸出。
(3)ViewGroupB處理事件
修改ViewGroupB代碼如下:
@Override
public boolean onTouchEvent(MotionEvent event) {
Log.d("DavidHuang------>","ViewGroupB # onTouchEvent");
return true;//表示當前View處理事件
// return super.onTouchEvent(event);
}
//ACTION_DOWN
ViewGroupA # dispatchTouchEvent
ViewGroupA # onInterceptTouchEvent
ViewGroupB # dispatchTouchEvent
ViewGroupB # onInterceptTouchEvent
ViewC # dispatchTouchEvent
ViewC # onTouchEvent
ViewGroupB # onTouchEvent
//ACTION_UP
ViewGroupA # dispatchTouchEvent
ViewGroupA # onInterceptTouchEvent
ViewGroupB # dispatchTouchEvent
ViewGroupB # onTouchEvent
既然ACTION_DOWN是ViewGroupB處理的,後續事件ACTION_UP直接傳遞給ViewGroupB處理,不會傳遞給ViewC,也不會再調用ViewGroupB#onInterceptTouchEvent方法。
(4)ViewGroupB攔截自己處理事件
修改ViewGroupB代碼如下:
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
Log.d("DavidHuang------>","ViewGroupB # onInterceptTouchEvent");
// return super.onInterceptTouchEvent(ev);
return true;
}
//ACTION_DOWN
ViewGroupA # dispatchTouchEvent
ViewGroupA # onInterceptTouchEvent
ViewGroupB # dispatchTouchEvent
ViewGroupB # onInterceptTouchEvent
ViewGroupB # onTouchEvent
//ACTION_UP
ViewGroupA # dispatchTouchEvent
ViewGroupA # onInterceptTouchEvent
ViewGroupB # dispatchTouchEvent
ViewGroupB # onTouchEvent
ViewGroupB攔截自己處理事件ACTION_DOWN,因此ViewGroupB # onInterceptTouchEvent返回true;同一事件序列中,當onInterceptTouchEvent()方法返回一個true,該方法不再被調用;所以雖然ACTION_UP是直接傳遞給ViewGroupB#onTouchEvent處理的,但並不會調用onInterceptTouchEvent方法。