在上一篇文章中說到的是關(guān)于View的事件分發(fā)機制桑阶,這篇文章就談一談關(guān)于ViewGroup的事件分發(fā)機制:
關(guān)于ViewGroup的事件分發(fā)機制,一般情況下行嗤,和View的情況是大致一樣的,只不過由于ViewGroup是一組View的集合,所以鹦倚,其中涉及到了子View,事件分發(fā)相對于View就多了一層冀惭,會稍微復(fù)雜一些震叙。那么下面就看看大神是如何分析的吧:
原文詳見:Android事件分發(fā)機制完全解析,帶你從源碼的角度徹底理解(下)
首先我們來探討一下散休,什么是ViewGroup媒楼?它和普通的View有什么區(qū)別?
顧名思義戚丸,ViewGroup就是一組View的集合划址,它包含很多的子View和子VewGroup,是Android中所有布局的父類或間接父類限府,像LinearLayout猴鲫、RelativeLayout等都是繼承自ViewGroup的。但ViewGroup實際上也是一個View谣殊,只不過比起View拂共,它多了可以包含子View和定義布局參數(shù)的功能。ViewGroup繼承結(jié)構(gòu)示意圖如下所示:
可以看到姻几,我們平時項目里經(jīng)常用到的各種布局宜狐,全都屬于ViewGroup的子類势告。
簡單介紹完了ViewGroup,我們現(xiàn)在通過一個Demo來演示一下Android中VewGroup的事件分發(fā)流程吧抚恒。
首先我們來自定義一個布局咱台,命名為MyLayout,繼承自LinearLayout俭驮,如下所示:
public class MyLayout extends LinearLayout {
public MyLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
}
然后回溺,打開主布局文件activity_main.xml,在其中加入我們自定義的布局:
<com.example.viewgrouptouchevent.MyLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/my_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button1" />
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button2" />
</com.example.viewgrouptouchevent.MyLayout>
可以看到混萝,我們在MyLayout中添加了兩個按鈕遗遵,接著在MainActivity中為這兩個按鈕和MyLayout都注冊了監(jiān)聽事件:
myLayout.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Log.d("TAG", "myLayout on touch");
return false;
}
});
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.d("TAG", "You clicked button1");
}
});
button2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.d("TAG", "You clicked button2");
}
});
我們在MyLayout的onTouch方法,和Button1逸嘀、Button2的onClick方法中都打印了一句話〕狄現(xiàn)在運行一下項目,效果圖如下所示:
分別點擊一下Button1崭倘、Button2和空白區(qū)域翼岁,打印結(jié)果如下所示:
你會發(fā)現(xiàn),當(dāng)點擊按鈕的時候司光,MyLayout注冊的onTouch方法并不會執(zhí)行琅坡,只有點擊空白區(qū)域的時候才會執(zhí)行該方法。你可以先理解成Button的onClick方法將事件消費掉了残家,因此事件不會再繼續(xù)向下傳遞榆俺。
那就說明Android中的touch事件是先傳遞到View,再傳遞到ViewGroup的跪削?現(xiàn)在下結(jié)論還未免過早了,讓我們再來做一個實驗迂求。
查閱文檔可以看到碾盐,ViewGroup中有一個onInterceptTouchEvent方法,我們來看一下這個方法的源碼:
/**
* Implement this method to intercept all touch screen motion events. This
* allows you to watch events as they are dispatched to your children, and
* take ownership of the current gesture at any point.
*
* <p>Using this function takes some care, as it has a fairly complicated
* interaction with {@link View#onTouchEvent(MotionEvent)
* View.onTouchEvent(MotionEvent)}, and using it requires implementing
* that method as well as this one in the correct way. Events will be
* received in the following order:
*
* <ol>
* <li> You will receive the down event here.
* <li> The down event will be handled either by a child of this view
* group, or given to your own onTouchEvent() method to handle; this means
* you should implement onTouchEvent() to return true, so you will
* continue to see the rest of the gesture (instead of looking for
* a parent view to handle it). Also, by returning true from
* onTouchEvent(), you will not receive any following
* events in onInterceptTouchEvent() and all touch processing must
* happen in onTouchEvent() like normal.
* <li> For as long as you return false from this function, each following
* event (up to and including the final up) will be delivered first here
* and then to the target's onTouchEvent().
* <li> If you return true from here, you will not receive any
* following events: the target view will receive the same event but
* with the action {@link MotionEvent#ACTION_CANCEL}, and all further
* events will be delivered to your onTouchEvent() method and no longer
* appear here.
* </ol>
*
* @param ev The motion event being dispatched down the hierarchy.
* @return Return true to steal motion events from the children and have
* them dispatched to this ViewGroup through onTouchEvent().
* The current target will receive an ACTION_CANCEL event, and no further
* messages will be delivered here.
*/
public boolean onInterceptTouchEvent(MotionEvent ev) {
return false;
}
如果不看源碼你還真可能被這注釋嚇到了揩局,這么長的英文注釋看得頭都大了毫玖。可是源碼竟然如此簡單凌盯!只有一行代碼付枫,返回了一個false!
好吧驰怎,既然是布爾型的返回阐滩,那么只有兩種可能,我們在MyLayout中重寫這個方法县忌,然后返回一個true試試掂榔,代碼如下所示:
public class MyLayout extends LinearLayout {
public MyLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return true;
}
}
現(xiàn)在再次運行項目继效,然后分別點擊Button1、Button2和空白區(qū)域装获,打印結(jié)果如下所示:
你會發(fā)現(xiàn)瑞信,不管你點擊哪里,永遠(yuǎn)都只會觸發(fā)MyLayout的touch事件了穴豫,按鈕的點擊事件完全被屏蔽掉了凡简!
這是為什么呢?
如果Android中的touch事件是先傳遞到View精肃,再傳遞到ViewGroup的秤涩,那么MyLayout又怎么可能屏蔽掉Button的點擊事件呢?看來只有通過閱讀源碼肋杖,搞清楚Android中ViewGroup的事件分發(fā)機制溉仑,才能解決我們心中的疑惑了,不過這里我想先跟你透露一句状植,Android中touch事件的傳遞浊竟,絕對是先傳遞到ViewGroup,再傳遞到View的津畸。
記得在Android事件分發(fā)機制完全解析振定,帶你從源碼的角度徹底理解(上) 中我有說明過,只要你觸摸了任何控件肉拓,就一定會調(diào)用該控件的dispatchTouchEvent方法后频。這個說法沒錯,只不過還不完整而已暖途。實際情況是杯缺,當(dāng)你點擊了某個控件,首先會去調(diào)用該控件所在布局的dispatchTouchEvent方法侧但,然后在布局的dispatchTouchEvent方法中找到被點擊的相應(yīng)控件看政,再去調(diào)用該控件的dispatchTouchEvent方法。如果我們點擊了MyLayout中的按鈕欺栗,會先去調(diào)用MyLayout的dispatchTouchEvent方法毫痕,可是你會發(fā)現(xiàn)MyLayout中并沒有這個方法。那就再到它的父類LinearLayout中找一找迟几,發(fā)現(xiàn)也沒有這個方法消请。那只好繼續(xù)再找LinearLayout的父類ViewGroup,你終于在ViewGroup中看到了這個方法类腮,按鈕的dispatchTouchEvent方法就是在這里調(diào)用的臊泰。
修改后的示意圖如下所示:
那還等什么?快去看一看ViewGroup中的dispatchTouchEvent方法的源碼吧蚜枢!代碼如下所示:
public boolean dispatchTouchEvent(MotionEvent ev) {
final int action = ev.getAction();
final float xf = ev.getX();
final float yf = ev.getY();
final float scrolledXFloat = xf + mScrollX;
final float scrolledYFloat = yf + mScrollY;
final Rect frame = mTempRect;
boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
if (action == MotionEvent.ACTION_DOWN) {
if (mMotionTarget != null) {
mMotionTarget = null;
}
if (disallowIntercept || !onInterceptTouchEvent(ev)) {
ev.setAction(MotionEvent.ACTION_DOWN);
final int scrolledXInt = (int) scrolledXFloat;
final int scrolledYInt = (int) scrolledYFloat;
final View[] children = mChildren;
final int count = mChildrenCount;
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);
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;
if (child.dispatchTouchEvent(ev)) {
mMotionTarget = child;
return true;
}
}
}
}
}
}
boolean isUpOrCancel = (action == MotionEvent.ACTION_UP) ||
(action == MotionEvent.ACTION_CANCEL);
if (isUpOrCancel) {
mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;
}
final View target = mMotionTarget;
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);
}
if (!disallowIntercept && onInterceptTouchEvent(ev)) {
final float xc = scrolledXFloat - (float) target.mLeft;
final float yc = scrolledYFloat - (float) target.mTop;
mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
ev.setAction(MotionEvent.ACTION_CANCEL);
ev.setLocation(xc, yc);
if (!target.dispatchTouchEvent(ev)) {
}
mMotionTarget = null;
return true;
}
if (isUpOrCancel) {
mMotionTarget = null;
}
final float xc = scrolledXFloat - (float) target.mLeft;
final float yc = scrolledYFloat - (float) target.mTop;
ev.setLocation(xc, yc);
if ((target.mPrivateFlags & CANCEL_NEXT_UP_EVENT) != 0) {
ev.setAction(MotionEvent.ACTION_CANCEL);
target.mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
mMotionTarget = null;
}
return target.dispatchTouchEvent(ev);
}
這個方法代碼比較長因宇,我們只挑重點看七婴。首先在第13行可以看到一個條件判斷,如果disallowIntercept和!onInterceptTouchEvent(ev)兩者有一個為true察滑,就會進(jìn)入到這個條件判斷中打厘。
disallowIntercept是指是否禁用掉事件攔截的功能,默認(rèn)是false贺辰,也可以通過調(diào)用requestDisallowInterceptTouchEvent方法對這個值進(jìn)行修改户盯。
那么當(dāng)?shù)谝粋€值為false的時候就會完全依賴第二個值來決定是否可以進(jìn)入到條件判斷的內(nèi)部,第二個值是什么呢饲化?竟然就是對onInterceptTouchEvent方法的返回值取反莽鸭!
也就是說如果我們在onInterceptTouchEvent方法中返回false,就會讓第二個值為true吃靠,從而進(jìn)入到條件判斷的內(nèi)部硫眨,如果我們在onInterceptTouchEvent方法中返回true,就會讓第二個值為false巢块,從而跳出了這個條件判斷礁阁。
這個時候你就可以思考一下了,由于我們剛剛在MyLayout中重寫了onInterceptTouchEvent方法族奢,讓這個方法返回true姥闭,導(dǎo)致所有按鈕的點擊事件都被屏蔽了,那我們就完全有理由相信越走,按鈕點擊事件的處理就是在第13行條件判斷的內(nèi)部進(jìn)行的棚品!
那我們重點來看下條件判斷的內(nèi)部是怎么實現(xiàn)的。在第19行通過一個for循環(huán)廊敌,遍歷了當(dāng)前ViewGroup下的所有子View铜跑,然后在第24行判斷當(dāng)前遍歷的View是不是正在點擊的View,如果是的話就會進(jìn)入到該條件判斷的內(nèi)部骡澈,然后在第29行調(diào)用了該View的dispatchTouchEvent锅纺,之后的流程就和 Android事件分發(fā)機制完全解析,帶你從源碼的角度徹底理解(上) 中講解的是一樣的了秧廉。我們也因此證實了伞广,按鈕點擊事件的處理確實就是在這里進(jìn)行的拣帽。
然后需要注意一下疼电,調(diào)用子View的dispatchTouchEvent后是有返回值的。我們已經(jīng)知道减拭,如果一個控件是可點擊的蔽豺,那么點擊該控件時,dispatchTouchEvent的返回值必定是true拧粪。因此會導(dǎo)致第29行的條件判斷成立修陡,于是在第31行給ViewGroup的dispatchTouchEvent方法直接返回了true沧侥。這樣就導(dǎo)致后面的代碼無法執(zhí)行到了,也是印證了我們前面的Demo打印的結(jié)果魄鸦,如果按鈕的點擊事件得到執(zhí)行宴杀,就會把MyLayout的touch事件攔截掉。
那如果我們點擊的不是按鈕拾因,而是空白區(qū)域呢旺罢?這種情況就一定不會在第31行返回true了,而是會繼續(xù)執(zhí)行后面的代碼绢记。那我們繼續(xù)往后看扁达,在第44行,如果target等于null蠢熄,就會進(jìn)入到該條件判斷內(nèi)部跪解,這里一般情況下target都會是null,因此會在第50行調(diào)用super.dispatchTouchEvent(ev)签孔。這句代碼會調(diào)用到哪里呢叉讥?當(dāng)然是View中的dispatchTouchEvent方法了,因為ViewGroup的父類就是View骏啰。之后的處理邏輯又和前面所說的是一樣的了节吮,也因此MyLayout中注冊的onTouch方法會得到執(zhí)行。之后的代碼在一般情況下是走不到的了判耕,我們也就不再繼續(xù)往下分析透绩。
再看一下整個ViewGroup事件分發(fā)過程的流程圖吧,相信可以幫助大家更好地去理解:
現(xiàn)在整個ViewGroup的事件分發(fā)流程的分析也就到此結(jié)束了壁熄,我們最后再來簡單梳理一下吧帚豪。
Android事件分發(fā)是先傳遞到ViewGroup,再由ViewGroup傳遞到View的草丧。
在ViewGroup中可以通過onInterceptTouchEvent方法對事件傳遞進(jìn)行攔截狸臣,onInterceptTouchEvent方法返回true代表不允許事件繼續(xù)向子View傳遞,返回false代表不對事件進(jìn)行攔截昌执,默認(rèn)返回false烛亦。
子View中如果將傳遞的事件消費掉,ViewGroup中將無法接收到任何事件懂拾。
好了煤禽,Android事件分發(fā)機制完全解析到此全部結(jié)束,結(jié)合上下兩篇岖赋,相信大家對事件分發(fā)的理解已經(jīng)非常深刻了檬果。
大神的分析已經(jīng)完畢,下面我個人的理解總結(jié)一下ViewGroup的全部的事件分發(fā)的過程:
對于最簡單的一個布局中含有一個按鈕,點擊按鈕的情況下选脊,事件是如何分發(fā)和傳遞的:
1杭抠、點擊按鈕的時候,首先執(zhí)行了ViewGroup的dispatchTouchEvent方法恳啥,觸發(fā)的是ViewGroup的MotionEvent.ACTION_DOWN事件偏灿。
在這個方法中,需要對兩個值進(jìn)行判斷:disallowIntercept和!onInterceptTouchEvent(ev)钝的;其中disallowIntercept是指是否禁用掉事件攔截的功能菩混,默認(rèn)是fasle,也可以通過調(diào)用requestDisallowInterceptTouchEvent()方法對這個值進(jìn)行修改扁藕。那么當(dāng)?shù)谝粋€值為false的時候沮峡,就需要對第二個值onInterceptTouchEvent(ev)進(jìn)行判斷,這個值是指中斷觸摸事件亿柑,可以通過重寫ViewGroup的onInterceptTouchEvent(MotionEvent ev)方法邢疙,對返回值進(jìn)行修改而改變,默認(rèn)是false望薄。當(dāng)這個判斷成立的時候疟游,就會進(jìn)入判斷內(nèi)部,對子View進(jìn)行遍歷痕支。否則颁虐,如果中斷了觸摸事件,即onInterceptTouchEvent(ev)值為true時卧须,子View的觸摸事件就會被中斷另绩,dispatchTouchEvent方法就返回了true。后續(xù)處理ViewGroup的touch事件花嘶。
2笋籽、對子View進(jìn)行遍歷,處理點擊的子View的事件椭员,觸發(fā)的是子View(這里為按鈕)的MotionEvent.ACTION_DOWN事件车海。
遍歷到點擊的子View時,對此View的dispatchTouchEvent方法的返回值進(jìn)行判斷隘击,即執(zhí)行了被點擊子View的dispatchTouchEvent方法侍芝,如果未進(jìn)行重寫,則執(zhí)行的是View的dispatchTouchEvent方法(源碼如下)埋同,在這個方法中州叠,有三個條件:
(1)判斷mOnTouchListener是否為null,其值是通過setOnTouchListener方法進(jìn)行賦值的莺禁,一般情況下留量,只處理子View的點擊事件的話窄赋,是不會對子View的OnTouchListener進(jìn)行賦值的哟冬,一般是null楼熄。
(2)判斷當(dāng)前點擊的控件是否是enable的,按鈕默認(rèn)是enable的(ViewGroup和ImageView默認(rèn)非enable)浩峡,這個值是true的可岂。
(3)mOnTouchListener.onTouch(this, event)是比較關(guān)鍵的一個值,這個值是對回調(diào)控件注冊touch事件時的onTouch方法翰灾。如果只是處理按鈕的點擊事件缕粹,不注冊子View的OnTouchListener事件的話,這個值是不用考慮的纸淮;如果注冊了子View的OnTouchListener事件平斩,并在onTouch方法里返回true,就會讓這三個條件全部成立咽块,從而整個方法直接返回true绘面。如果我們在onTouch方法里返回false,就會再去執(zhí)行onTouchEvent(event)方法侈沪。
3揭璃、處理子View即按鈕的點擊事件,觸發(fā)的是子View(這里為按鈕)的MotionEvent.ACTION_UP事件:
如果不注冊子View的OnTouchListener事件亭罪,就會在View的dispatchTouchEvent方法中返回View的OnTouchEvent(event)的值(默認(rèn)是false的)瘦馍,在onTouch的方法中調(diào)用了子View的onClick方法,在MotionEvent.ACTION_UP事件中应役,執(zhí)行了performClick()方法(代碼如下)情组,在這個方法中,對子View的onClick方法進(jìn)行了處理箩祥。最終返回了true呻惕,終止了事件繼續(xù)傳遞(即子View的dispatchTouchEvent方法最終返回了true)。
public boolean dispatchTouchEvent(MotionEvent event) {
if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED &&
mOnTouchListener.onTouch(this, event)) {
return true;
}
return onTouchEvent(event);
}
public boolean performClick() {
sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
if (mOnClickListener != null) {
playSoundEffect(SoundEffectConstants.CLICK);
mOnClickListener.onClick(this);
return true;
}
return false;
}
注:
這里說明一下為什么點擊空白處的時候滥比,運行的結(jié)果也和點擊imageview一樣亚脆,就是因為ViewGroup默認(rèn)的clickable是false,導(dǎo)致在處理ViewGroup的OnTouch方法時盲泛,由于是不可點擊的濒持,其中的onClick方法并未執(zhí)行。
可以試驗一下寺滚,加上如下代碼:
myLayout.setClickable(true);
運行一下程序柑营,點擊空白處,你會發(fā)現(xiàn)結(jié)果如下:
Demo下載地址:http://download.csdn.NET/detail/shengfeixiang/7507363