所謂事件分發,就是將一次完整的點擊所包含的點擊事件傳遞到某個具體的View或ViewGroup,讓該View或該ViewGroup處理它(消費它)。分發是從上往下(父到子)依次傳遞的,其中可能通過的對象有最上層Activity,中間層ViewGroup,最下層View。java
源碼查找:
1.本身的Activity的setContentView()
方法android
@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
app
mWindow = new PhoneWindow(this, window, activityConfigCallback);
4.PhoneWindow.java-->setContentView()--> installDecor(),在PhoneWindow中調用了installDecor()
方法ide
@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
根據不一樣狀況,返回不一樣的資源文件,也就是佈局文件。this
int layoutResource;
8.PhoneWindow.java-->generateLayout()-->R.layout.screen_title; 拿出一個經常使用的佈局文件,screen_title.xml
spa
layoutResource = R.layout.screen_title;
9.screen_title.xml的代碼, ViewStub
是用來顯示ActionBar
的,另外兩個FrameLayout,一個顯示TitleView
,一個顯示ContentView,平時寫的內容,正是ContentView
。rest
<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()
每一次事件分發,都是從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()
方法。
6)返回值分析。
getWindow().superDispatchTouchEvent()
返回true,則Avtivity的dispatchTouchEvent(),也會返回true,表示點擊事件順利分發給ViewGroup,由ViewGroup繼續進行下一層的分發,Avtivity的分發任務結束。onTouchEvent()
,不管onTouchEvent()
這個方法返回的是true或者false,本次的事件分發都結束了。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)
方法
onInterceptTouchEvent(ev)
默認返回不攔截,能夠在ViewGroup中重寫改方法來攔截事件。這個源碼中,使用到了intercepted這個變量,主要做用是來遍歷子ViewGroup和View,
// 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;
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; }
onTouch()
方法,若是onTouch()方法可以消費該事件,就會直接返回True,從而直接結束View的dispatchTouchEvent()方法,再也不執行onTouchEvent()方法;onTouchEvent
`()`方法。ViewGroup
的onTouchEvent()方法,直到回調到Activity的onTouchEvent
`()`方法。共有三種類型和四個測試代碼
Activity:EventDistributionActivity
ViewGroup:EventDistributionLinearLayout一、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
界面只有一個按鈕
測試用例:按鈕消費事件,和空白處不消費事件
按住按鈕不鬆開,事件被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
測試用例:在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
測試用例:在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
編程中咱們會遇到多少挫折?表放棄,沙漠盡頭必是綠洲。