一、什么是事件分發
所謂事件分發,就是將一次完整的點擊所包含的點擊事件傳遞到某個具體的View或ViewGroup,讓該View或該ViewGroup處理它(消費它),分發是從上往下(父到子)依次傳遞的,其中可能經過的物件有最上層Activity,中間層ViewGroup,最下層View,
二、Activity的層次結構
原始碼查找:
1.自己的Activity的setContentView()方法
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_distribution);
}
2.跳轉到Activity.java的setContentView()方法,可以看到,呼叫了getWindow()的方法
public void setContentView(@LayoutRes int layoutResID) {
getWindow().setContentView(layoutResID);
initWindowDecorActionBar();
}
3.Activity.java的mWindow來自PhoneWindow
mWindow = new PhoneWindow(this, window, activityConfigCallback);
4.PhoneWindow.java-->setContentView()--> installDecor(),在PhoneWindow中呼叫了installDecor()方法
@Override
public void setContentView(int layoutResID) {
// Note: FEATURE_CONTENT_TRANSITIONS may be set in the process of installing the window
// decor, when theme attributes and the like are crystalized. Do not check the feature
// before this happens.
if (mContentParent == null) {
installDecor(); //繼續執行
} else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
mContentParent.removeAllViews();
}
..................
5.PhoneWindow.java-->setContentView()--> installDecor()--> generateLayout(mDecor),在 installDecor()中又繼續執行了generateLayout(mDecor)方法,
mContentParent = generateLayout(mDecor);
6.PhoneWindow.java-->generateLayout()
ViewGroup generateLayout(DecorView decor)
7.PhoneWindow.java-->generateLayout()--> int layoutResource,layoutResource根據不同情況,回傳不同的資源檔案,也就是布局檔案,
int layoutResource;
8.PhoneWindow.java-->generateLayout()-->R.layout.screen_title; 拿出一個常用的布局檔案,screen_title.xml
layoutResource = R.layout.screen_title;
9.screen_title.xml的代碼, ViewStub是用來顯示ActionBar的,另外兩個FrameLayout,一個顯示TitleView,一個顯示ContentView,平時寫的內容,正是ContentView,
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:fitsSystemWindows="true">
<!-- Popout bar for action modes -->
<ViewStub android:id="@+id/action_mode_bar_stub"
android:inflatedId="@+id/action_mode_bar"
android:layout="@layout/action_mode_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="?attr/actionBarTheme" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="?android:attr/windowTitleSize"
style="?android:attr/windowTitleBackgroundStyle">
<TextView android:id="@android:id/title"
style="?android:attr/windowTitleStyle"
android:background="@null"
android:fadingEdge="horizontal"
android:gravity="center_vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
<FrameLayout android:id="@android:id/content"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:foregroundGravity="fill_horizontal|top"
android:foreground="?android:attr/windowContentOverlay" />
</LinearLayout>
如以下結構圖:

三、事件分發涉及到的主要方法
涉及到的方法
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
//分發事件
return super.dispatchTouchEvent(ev);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
//攔截事件
return super.onInterceptTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
//消費事件
return super.onTouchEvent(event);
}
Activity涉及到的方法:dispatchTouchEvent()、onTouchEvent()
ViewGroup涉及到的方法:dispatchTouchEvent()、onInterceptTouchEvent()
View涉及到的方法:dispatchTouchEvent()、onTouchEvent()
四、事件分發流程
1.Activity把事件分發到ViewGroup
(1)事件傳遞
每一次事件分發,都是從dispatchTouchEvent()開始的,
1)查看Activity的原始碼,呼叫了getWindow().superDispatchTouchEvent(ev)
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
onUserInteraction();
}
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
}
2)在Activity.java中可以看到,所以getWindow().superDispatchTouchEvent(ev)實際上是呼叫了PhoneWindow.java中的superDispatchTouchEvent(ev)方法,
public Window getWindow() {
return mWindow;
}
mWindow = new PhoneWindow(this, window, activityConfigCallback); //mWindow的定義
3)然后再看PhoneWindow.java中的superDispatchTouchEvent(ev)方法,是呼叫DecorView.java的mDecor.superDispatchTouchEvent(event)
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
return mDecor.superDispatchTouchEvent(event);
}
4)而DecorView是繼承FrameLayout,再繼承ViewGroup的
private DecorView mDecor; //實體物件
class DecorView extends FrameLayout; //繼承FrameLayout
FrameLayout extends ViewGroup; //繼承ViewGroup
5)從上面四步來分析,Avtivity的getWindow().superDispatchTouchEvent()方法最后呼叫的是ViewGroup的dispatchTouchEvent()方法,從而實作了事件從Activity的dispatchTouchEvent()向下傳遞到ViewGroup的dispatchTouchEvent()方法,
(2)總結
6)回傳值分析,
- 如果Avtivity的
getWindow().superDispatchTouchEvent()回傳true,則Avtivity的dispatchTouchEvent(),也會回傳true,表示點擊事件順利分發給ViewGroup,由ViewGroup繼續進行下一層的分發,Avtivity的分發任務結束, - 如果回傳false,表示此次點擊事件由Avtivity層消費,會執行Avtivity的
onTouchEvent(),無論onTouchEvent()這個方法回傳的是true或者false,本次的事件分發都結束了,
(3)流程圖

2.ViewGroup把事件分發到ViewGroup或View
(1)事件攔截
ViewGroup.java中的部分代碼
ViewGroup-->dispatchTouchEvent()
public boolean dispatchTouchEvent(MotionEvent ev) {
if (!disallowIntercept) {
intercepted = onInterceptTouchEvent(ev);
ev.setAction(action); // restore action in case it was changed
} else {
intercepted = false;
}
}
方法中使用了onInterceptTouchEvent(ev)方法
- 如果回傳true,則表示ViewGroup攔截此次事件,
- 如果回傳false,則表示ViewGroup不攔截,事件繼續往下分發,
onInterceptTouchEvent(ev)默認回傳不攔截,可以在ViewGroup中重寫改方法來攔截事件,- 不攔截事件,則會呼叫ViewGroup的onTouchEvent()來處理點擊事件,把事件消費掉,
(2)分發
這個原始碼中,使用到了intercepted這個變數,主要作用是來遍歷子ViewGroup和View,
- 當intercepted為false的時候,遍歷子ViewGroup和子View,因為這個事件沒有被消費掉,繼續分發到子ViewGroup和子View,
- 當intercepted為true的時候,該事件已經被消費,不會繼續往下分發,也不會遍歷子ViewGroup和子View,也不會執行if陳述句里面的方法,
- 進入if陳述句中判斷點擊事件的觸摸范圍(焦點)是否屬于某個子ViewGroup或者子View,
- 如果觸摸范圍屬于子View,則呼叫子View的dispatchTouchEvent()方法,
- 如果觸摸范圍屬于子ViewGroup,則繼續遍歷下一層的ViewGroup或者View,
- 遍歷到最下層的View,還是找不到消費此處事件的View,則依次回呼上一層的ViewGroup的onTouchEvent()方法,直到回呼到Activity的onTouchEvent()方法,
// Check for interception.
final boolean intercepted;
if (!canceled && !intercepted) {
// If the event is targeting accessibility focus we give it to the
// view that has accessibility focus and if it does not handle it
// we clear the flag and dispatch the event to all children as usual.
// We are looking up the accessibility focused host to avoid keeping
// state since these events are very rare.
View childWithAccessibilityFocus = ev.isTargetAccessibilityFocus()
? findChildWithAccessibilityFocus() : null;
(3)流程圖

3.View的事件分發
(1)分析
View的dispatchTouchEvent()的原始碼
public boolean dispatchTouchEvent(MotionEvent event) {
// If the event should be handled by accessibility focus first.
if (event.isTargetAccessibilityFocus()) {
// We don't have focus or no virtual descendant has it, do not handle the event.
if (!isAccessibilityFocusedViewOrHost()) {
return false;
}
// We have focus and got the event, then use normal event dispatch.
event.setTargetAccessibilityFocus(false);
}
boolean result = false;
if (mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onTouchEvent(event, 0);
}
final int actionMasked = event.getActionMasked();
if (actionMasked == MotionEvent.ACTION_DOWN) {
// Defensive cleanup for new gesture
stopNestedScroll();
}
if (onFilterTouchEventForSecurity(event)) {
if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
result = true;
}
//noinspection SimplifiableIfStatement
ListenerInfo li = mListenerInfo;
if (li != null && li.mOnTouchListener != null
&& (mViewFlags & ENABLED_MASK) == ENABLED
&& li.mOnTouchListener.onTouch(this, event)) {
result = true;
}
if (!result && onTouchEvent(event)) {
result = true;
}
}
if (!result && mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
}
// Clean up after nested scrolls if this is the end of a gesture;
// also cancel it if we tried an ACTION_DOWN but we didn't want the rest
// of the gesture.
if (actionMasked == MotionEvent.ACTION_UP ||
actionMasked == MotionEvent.ACTION_CANCEL ||
(actionMasked == MotionEvent.ACTION_DOWN && !result)) {
stopNestedScroll();
}
return result;
}
- 在View的dispatchTouchEvent()方法中首先會呼叫
onTouch()方法,如果onTouch()方法能夠消費該事件,就會直接回傳True,從而直接結束View的dispatchTouchEvent()方法,不再執行onTouchEvent()方法; - 如果onTouch()方法不能消費該事件,就會回傳False,從而繼續執行
onTouchEvent``()方法, - 如果onTouchEvent()能夠消費該事件,就會回傳True從而直接結束dispatchTouchEvent()方法,
- 如果onTouchEvent()方法也不能消費該事件,就會回傳默認的False從而回呼到上一層
ViewGroup的onTouchEvent()方法,直到回呼到Activity的onTouchEvent``()方法,
(2)流程圖

五、具體例子
(0)測驗代碼
共有三種型別和四個測驗代碼
Activity:EventDistributionActivity
ViewGroup:EventDistributionLinearLayout1、EventDistributionLinearLayout2
View:EventDistributionButton
分別代碼:
EventDistributionActivity.java
public class EventDistributionActivity extends BaseActivity {
Button mBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_distribution);
mBtn = findViewById(R.id.btn);
OnClick();
}
public void OnClick() {
mBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.v("showLog", "按鈕被點擊!");
}
});
mBtn.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
boolean dis = false;
Log.v("showLog", "Button.Touch()=" + dis);
return dis;
}
});
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
//分發事件
boolean dis = super.dispatchTouchEvent(ev);
Log.v("showLog", "Activity.dispatchTouchEvent()=" + dis);
return dis;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
//處理事件
boolean dis = super.onTouchEvent(event);
Log.v("showLog", "Activity.onTouchEvent()=" + dis);
return dis;
}
}
EventDistributionLinearLayout1.java
public class EventDistributionLinearLayout1 extends LinearLayout {
public EventDistributionLinearLayout1(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
//分發事件
boolean dis = super.dispatchTouchEvent(ev);
Log.v("showLog", "LinearLayout1.dispatchTouchEvent()=" + dis);
return dis;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
//攔截事件
boolean dis = super.onInterceptTouchEvent(ev);
Log.v("showLog", "LinearLayout1.onInterceptTouchEvent()=" + dis);
return dis;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
//消費事件
boolean dis = super.onTouchEvent(event);
Log.v("showLog", "LinearLayout1.onTouchEvent()=" + dis);
return dis;
}
}
EventDistributionLinearLayout2.java
public class EventDistributionLinearLayout2 extends LinearLayout {
public EventDistributionLinearLayout2(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
//分發事件
boolean dis = super.dispatchTouchEvent(ev);
Log.v("showLog", "LinearLayout2.dispatchTouchEvent()=" + dis);
return dis;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
//攔截事件
boolean dis = super.onInterceptTouchEvent(ev);
dis = true;
Log.v("showLog", "LinearLayout2.onInterceptTouchEvent()=" + dis);
return dis;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
//消費事件
boolean dis = super.onTouchEvent(event);
Log.v("showLog", "LinearLayout2.onTouchEvent()=" + dis);
return dis;
}
}
EventDistributionButton.java
public class EventDistributionButton extends Button {
public EventDistributionButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
//分發事件
boolean dis = super.dispatchTouchEvent(event);
Log.v("showLog", "Button.dispatchTouchEvent()=" + dis);
return dis;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
//消費事件
boolean dis = super.onTouchEvent(event);
Log.v("showLog", "Button.onTouchEvent()=" + dis);
return dis;
}
@Override
public boolean performClick() {
boolean dis = super.performClick();
Log.v("showLog", "Button.performClick()="+dis);
return dis;
}
}
activity_event_distribution.xml
<?xml version="1.0" encoding="utf-8"?>
<com.lanjiabin.systemtest.event.EventDistributionLinearLayout1 xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".event.EventDistributionActivity">
<com.lanjiabin.systemtest.event.EventDistributionLinearLayout2
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.lanjiabin.systemtest.event.EventDistributionButton
android:background="@drawable/button_color_circle_shape1"
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="300dp"
android:text="點擊" />
</com.lanjiabin.systemtest.event.EventDistributionLinearLayout2>
</com.lanjiabin.systemtest.event.EventDistributionLinearLayout1>
效果圖:一個LinearLayout1包含LinearLayout2再包含一個Button
界面只有一個按鈕

(1)測驗1
測驗用例:按鈕消費事件,和空白處不消費事件
按住按鈕不松開,事件被Button的onTouchEvent()消費
LinearLayout1.onInterceptTouchEvent()=false
LinearLayout2.onInterceptTouchEvent()=false
Button.Touch()=false
Button.onTouchEvent()=true
Button.dispatchTouchEvent()=true
LinearLayout2.dispatchTouchEvent()=true
LinearLayout1.dispatchTouchEvent()=true
Activity.dispatchTouchEvent()=true
按住空白處不松開,沒有事件被消費
LinearLayout1.onInterceptTouchEvent()=false
LinearLayout2.onInterceptTouchEvent()=false
LinearLayout2.onTouchEvent()=false
LinearLayout2.dispatchTouchEvent()=false
LinearLayout1.onTouchEvent()=false
LinearLayout1.dispatchTouchEvent()=false
Activity.onTouchEvent()=false
Activity.dispatchTouchEvent()=false
(2)測驗2
測驗用例:在LinearLayout2處截斷
修改代碼:EventDistributionLinearLayout2.java
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
//攔截事件
boolean dis = super.onInterceptTouchEvent(ev);
dis = true;
Log.v("showLog", "LinearLayout2.onInterceptTouchEvent()=" + dis);
return dis;
}
按住按鈕不松開:事件截斷生效,將不會繼續遍歷下層的ViewGroup或者View,所以日志中看不到Button的日志列印,
LinearLayout1.onInterceptTouchEvent()=false
LinearLayout2.onInterceptTouchEvent()=true //截斷生效
LinearLayout2.onTouchEvent()=false
LinearLayout2.dispatchTouchEvent()=false
LinearLayout1.onTouchEvent()=false
LinearLayout1.dispatchTouchEvent()=false
Activity.onTouchEvent()=false
Activity.dispatchTouchEvent()=false
(3)測驗3
測驗用例:在View中onTouch()中回傳true
也就是在Button中設定onTouch()回傳true,則不會產生點擊事件,完整的點擊事件是被按下和松開的,所以上面沒有點擊按鈕的監聽事件的列印日志,
首先,看看完整的點擊事件日志,去掉先前測驗的改變的代碼,
LinearLayout1.onInterceptTouchEvent()=false
LinearLayout2.onInterceptTouchEvent()=false
Button.Touch()=false
Button.onTouchEvent()=true //觸摸按下事件被消費
Button.dispatchTouchEvent()=true
LinearLayout2.dispatchTouchEvent()=true
LinearLayout1.dispatchTouchEvent()=true
Activity.dispatchTouchEvent()=true //觸摸按下的事件處理結束
LinearLayout1.onInterceptTouchEvent()=false //開始觸摸i抬起的事件
LinearLayout2.onInterceptTouchEvent()=false
Button.Touch()=false
Button.onTouchEvent()=true //觸摸抬起的事件被消費
Button.dispatchTouchEvent()=true
LinearLayout2.dispatchTouchEvent()=true
LinearLayout1.dispatchTouchEvent()=true
Activity.dispatchTouchEvent()=true
按鈕被點擊! //onClick
Button.performClick()=true
開始測驗用例:
修改代碼:
EventDistributionActivity.java,將boolean dis = false;修改為boolean dis = true;
mBtn.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
boolean dis = true;
Log.v("showLog", "Button.Touch()=" + dis);
return dis;
}
});
按下和松開按鈕:可以看到,事件被Button.Touch()消費了,因為在Touch()回傳了true,事件沒有繼續傳遞下去,所以onClick事件沒有被觸發,沒有生效,
LinearLayout1.onInterceptTouchEvent()=false
LinearLayout2.onInterceptTouchEvent()=false
Button.Touch()=true //觸摸事件被消費
Button.dispatchTouchEvent()=true
LinearLayout2.dispatchTouchEvent()=true
LinearLayout1.dispatchTouchEvent()=true
Activity.dispatchTouchEvent()=true //觸摸按下事件處理完畢
LinearLayout1.onInterceptTouchEvent()=false
LinearLayout2.onInterceptTouchEvent()=false
Button.Touch()=true
Button.dispatchTouchEvent()=true
LinearLayout2.dispatchTouchEvent()=true
LinearLayout1.dispatchTouchEvent()=true
Activity.dispatchTouchEvent()=true
編程中我們會遇到多少挫折?表放棄,沙漠盡頭必是綠洲,
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/4143.html
標籤:Android
