首先我們來(lái)探討一下什乙,什么是ViewGroup?它和普通的View有什么區(qū)別已球?
顧名思義臣镣,ViewGroup就是一組View的集合,它包含很多的子View和子VewGroup智亮,是Android中所有布局的父類(lèi)或間接父類(lèi)忆某,像LinearLayout、RelativeLayout等都是繼承自ViewGroup的阔蛉。但ViewGroup實(shí)際上也是一個(gè)View弃舒,只不過(guò)比起View,它多了可以包含子View和定義布局參數(shù)的功能。ViewGroup繼承結(jié)構(gòu)示意圖如下所示:
可以看到聋呢,我們平時(shí)項(xiàng)目里經(jīng)常用到的各種布局苗踪,全都屬于ViewGroup的子類(lèi)。
簡(jiǎn)單介紹完了ViewGroup削锰,我們現(xiàn)在通過(guò)一個(gè)Demo來(lái)演示一下Android中VewGroup的事件分發(fā)流程吧通铲。
首先我們來(lái)自定義一個(gè)布局,命名為MyLayout器贩,繼承自L(fǎng)inearLayout颅夺,如下所示:
[java]
publicclassMyLayoutextendsLinearLayout?{
publicMyLayout(Context?context,?AttributeSet?attrs)?{
super(context,?attrs);
}
}
然后,打開(kāi)主布局文件activity_main.xml蛹稍,在其中加入我們自定義的布局:
[html]view plaincopy
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">
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button1"/>
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button2"/>
可以看到吧黄,我們?cè)贛yLayout中添加了兩個(gè)按鈕,接著在MainActivity中為這兩個(gè)按鈕和MyLayout都注冊(cè)了監(jiān)聽(tīng)事件:
[java]view plaincopy
myLayout.setOnTouchListener(newOnTouchListener()?{
@Override
publicbooleanonTouch(View?v,?MotionEvent?event)?{
Log.d("TAG","myLayout?on?touch");
returnfalse;
}
});
button1.setOnClickListener(newOnClickListener()?{
@Override
publicvoidonClick(View?v)?{
Log.d("TAG","You?clicked?button1");
}
});
button2.setOnClickListener(newOnClickListener()?{
@Override
publicvoidonClick(View?v)?{
Log.d("TAG","You?clicked?button2");
}
});
我們?cè)贛yLayout的onTouch方法唆姐,和Button1稚字、Button2的onClick方法中都打印了一句話(huà)。現(xiàn)在運(yùn)行一下項(xiàng)目厦酬,效果圖如下所示:
分別點(diǎn)擊一下Button1胆描、Button2和空白區(qū)域,打印結(jié)果如下所示:
你會(huì)發(fā)現(xiàn)仗阅,當(dāng)點(diǎn)擊按鈕的時(shí)候昌讲,MyLayout注冊(cè)的onTouch方法并不會(huì)執(zhí)行,只有點(diǎn)擊空白區(qū)域的時(shí)候才會(huì)執(zhí)行該方法减噪。你可以先理解成Button的onClick方法將事件消費(fèi)掉了短绸,因此事件不會(huì)再繼續(xù)向下傳遞。
那就說(shuō)明Android中的touch事件是先傳遞到View筹裕,再傳遞到ViewGroup的醋闭?現(xiàn)在下結(jié)論還未免過(guò)早了,讓我們?cè)賮?lái)做一個(gè)實(shí)驗(yàn)朝卒。
查閱文檔可以看到证逻,ViewGroup中有一個(gè)onInterceptTouchEvent方法,我們來(lái)看一下這個(gè)方法的源碼:
[java]view plaincopy
/**
*?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.
*
*?
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:
*
*?
*?
?You?will?receive?the?down?event?here.
*?
?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.
*?
?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().
*?
?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.
*?
*
*?@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.
*/
publicbooleanonInterceptTouchEvent(MotionEvent?ev)?{
returnfalse;
}
如果不看源碼你還真可能被這注釋嚇到了抗斤,這么長(zhǎng)的英文注釋看得頭都大了囚企。可是源碼竟然如此簡(jiǎn)單瑞眼!只有一行代碼龙宏,返回了一個(gè)false!
好吧伤疙,既然是布爾型的返回银酗,那么只有兩種可能,我們?cè)贛yLayout中重寫(xiě)這個(gè)方法,然后返回一個(gè)true試試黍特,代碼如下所示:
[java]view plaincopy
publicclassMyLayoutextendsLinearLayout?{
publicMyLayout(Context?context,?AttributeSet?attrs)?{
super(context,?attrs);
}
@Override
publicbooleanonInterceptTouchEvent(MotionEvent?ev)?{
returntrue;
}
}
現(xiàn)在再次運(yùn)行項(xiàng)目蛙讥,然后分別Button1、Button2和空白區(qū)域衅澈,打印結(jié)果如下所示:
你會(huì)發(fā)現(xiàn)键菱,不管你點(diǎn)擊哪里谬墙,永遠(yuǎn)都只會(huì)觸發(fā)MyLayout的touch事件了今布,按鈕的點(diǎn)擊事件完全被屏蔽掉了!這是為什么呢拭抬?如果Android中的touch事件是先傳遞到View部默,再傳遞到ViewGroup的,那么MyLayout又怎么可能屏蔽掉Button的點(diǎn)擊事件呢造虎?
看來(lái)只有通過(guò)閱讀源碼傅蹂,搞清楚Android中ViewGroup的事件分發(fā)機(jī)制,才能解決我們心中的疑惑了算凿,不過(guò)這里我想先跟你透露一句份蝴,Android中touch事件的傳遞,絕對(duì)是先傳遞到ViewGroup氓轰,再傳遞到View的婚夫。記得在Android事件分發(fā)機(jī)制完全解析,帶你從源碼的角度徹底理解(上)中我有說(shuō)明過(guò)署鸡,只要你觸摸了任何控件案糙,就一定會(huì)調(diào)用該控件的dispatchTouchEvent方法。這個(gè)說(shuō)法沒(méi)錯(cuò)靴庆,只不過(guò)還不完整而已时捌。實(shí)際情況是,當(dāng)你點(diǎn)擊了某個(gè)控件炉抒,首先會(huì)去調(diào)用該控件所在布局的dispatchTouchEvent方法奢讨,然后在布局的dispatchTouchEvent方法中找到被點(diǎn)擊的相應(yīng)控件,再去調(diào)用該控件的dispatchTouchEvent方法焰薄。如果我們點(diǎn)擊了MyLayout中的按鈕禽笑,會(huì)先去調(diào)用MyLayout的dispatchTouchEvent方法,可是你會(huì)發(fā)現(xiàn)MyLayout中并沒(méi)有這個(gè)方法蛤奥。那就再到它的父類(lèi)LinearLayout中找一找佳镜,發(fā)現(xiàn)也沒(méi)有這個(gè)方法。那只好繼續(xù)再找LinearLayout的父類(lèi)ViewGroup凡桥,你終于在ViewGroup中看到了這個(gè)方法蟀伸,按鈕的dispatchTouchEvent方法就是在這里調(diào)用的。修改后的示意圖如下所示:
那還等什么?快去看一看ViewGroup中的dispatchTouchEvent方法的源碼吧啊掏!代碼如下所示:
[java]view plaincopy
publicbooleandispatchTouchEvent(MotionEvent?ev)?{
finalintaction?=?ev.getAction();
finalfloatxf?=?ev.getX();
finalfloatyf?=?ev.getY();
finalfloatscrolledXFloat?=?xf?+?mScrollX;
finalfloatscrolledYFloat?=?yf?+?mScrollY;
finalRect?frame?=?mTempRect;
booleandisallowIntercept?=?(mGroupFlags?&?FLAG_DISALLOW_INTERCEPT)?!=0;
if(action?==?MotionEvent.ACTION_DOWN)?{
if(mMotionTarget?!=null)?{
mMotionTarget?=null;
}
if(disallowIntercept?||?!onInterceptTouchEvent(ev))?{
ev.setAction(MotionEvent.ACTION_DOWN);
finalintscrolledXInt?=?(int)?scrolledXFloat;
finalintscrolledYInt?=?(int)?scrolledYFloat;
finalView[]?children?=?mChildren;
finalintcount?=?mChildrenCount;
for(inti?=?count?-1;?i?>=0;?i--)?{
finalView?child?=?children[i];
if((child.mViewFlags?&?VISIBILITY_MASK)?==?VISIBLE
||?child.getAnimation()?!=null)?{
child.getHitRect(frame);
if(frame.contains(scrolledXInt,?scrolledYInt))?{
finalfloatxc?=?scrolledXFloat?-?child.mLeft;
finalfloatyc?=?scrolledYFloat?-?child.mTop;
ev.setLocation(xc,?yc);
child.mPrivateFlags?&=?~CANCEL_NEXT_UP_EVENT;
if(child.dispatchTouchEvent(ev))??{
mMotionTarget?=?child;
returntrue;
}
}
}
}
}
}
booleanisUpOrCancel?=?(action?==?MotionEvent.ACTION_UP)?||
(action?==?MotionEvent.ACTION_CANCEL);
if(isUpOrCancel)?{
mGroupFlags?&=?~FLAG_DISALLOW_INTERCEPT;
}
finalView?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;
}
returnsuper.dispatchTouchEvent(ev);
}
if(!disallowIntercept?&&?onInterceptTouchEvent(ev))?{
finalfloatxc?=?scrolledXFloat?-?(float)?target.mLeft;
finalfloatyc?=?scrolledYFloat?-?(float)?target.mTop;
mPrivateFlags?&=?~CANCEL_NEXT_UP_EVENT;
ev.setAction(MotionEvent.ACTION_CANCEL);
ev.setLocation(xc,?yc);
if(!target.dispatchTouchEvent(ev))?{
}
mMotionTarget?=null;
returntrue;
}
if(isUpOrCancel)?{
mMotionTarget?=null;
}
finalfloatxc?=?scrolledXFloat?-?(float)?target.mLeft;
finalfloatyc?=?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;
}
returntarget.dispatchTouchEvent(ev);
}
這個(gè)方法代碼比較長(zhǎng)蠢络,我們只挑重點(diǎn)看。首先在第13行可以看到一個(gè)條件判斷迟蜜,如果disallowIntercept和!onInterceptTouchEvent(ev)兩者有一個(gè)為true刹孔,就會(huì)進(jìn)入到這個(gè)條件判斷中。disallowIntercept是指是否禁用掉事件攔截的功能娜睛,默認(rèn)是false髓霞,也可以通過(guò)調(diào)用requestDisallowInterceptTouchEvent方法對(duì)這個(gè)值進(jìn)行修改。那么當(dāng)?shù)谝粋€(gè)值為false的時(shí)候就會(huì)完全依賴(lài)第二個(gè)值來(lái)決定是否可以進(jìn)入到條件判斷的內(nèi)部畦戒,第二個(gè)值是什么呢方库?竟然就是對(duì)onInterceptTouchEvent方法的返回值取反!也就是說(shuō)如果我們?cè)趏nInterceptTouchEvent方法中返回false障斋,就會(huì)讓第二個(gè)值為true纵潦,從而進(jìn)入到條件判斷的內(nèi)部,如果我們?cè)趏nInterceptTouchEvent方法中返回true垃环,就會(huì)讓第二個(gè)值為false邀层,從而跳出了這個(gè)條件判斷。
這個(gè)時(shí)候你就可以思考一下了遂庄,由于我們剛剛在MyLayout中重寫(xiě)了onInterceptTouchEvent方法寥院,讓這個(gè)方法返回true,導(dǎo)致所有按鈕的點(diǎn)擊事件都被屏蔽了涧团,那我們就完全有理由相信只磷,按鈕點(diǎn)擊事件的處理就是在第13行條件判斷的內(nèi)部進(jìn)行的!
那我們重點(diǎn)來(lái)看下條件判斷的內(nèi)部是怎么實(shí)現(xiàn)的泌绣。在第19行通過(guò)一個(gè)for循環(huán)钮追,遍歷了當(dāng)前ViewGroup下的所有子View,然后在第24行判斷當(dāng)前遍歷的View是不是正在點(diǎn)擊的View阿迈,如果是的話(huà)就會(huì)進(jìn)入到該條件判斷的內(nèi)部元媚,然后在第29行調(diào)用了該View的dispatchTouchEvent,之后的流程就和Android事件分發(fā)機(jī)制完全解析苗沧,帶你從源碼的角度徹底理解(上)中講解的是一樣的了刊棕。我們也因此證實(shí)了,按鈕點(diǎn)擊事件的處理確實(shí)就是在這里進(jìn)行的待逞。
然后需要注意一下甥角,調(diào)用子View的dispatchTouchEvent后是有返回值的。我們已經(jīng)知道识樱,如果一個(gè)控件是可點(diǎn)擊的嗤无,那么點(diǎn)擊該控件時(shí)震束,dispatchTouchEvent的返回值必定是true。因此會(huì)導(dǎo)致第29行的條件判斷成立当犯,于是在第31行給ViewGroup的dispatchTouchEvent方法直接返回了true垢村。這樣就導(dǎo)致后面的代碼無(wú)法執(zhí)行到了,也是印證了我們前面的Demo打印的結(jié)果嚎卫,如果按鈕的點(diǎn)擊事件得到執(zhí)行嘉栓,就會(huì)把MyLayout的touch事件攔截掉。
那如果我們點(diǎn)擊的不是按鈕拓诸,而是空白區(qū)域呢侵佃?這種情況就一定不會(huì)在第31行返回true了,而是會(huì)繼續(xù)執(zhí)行后面的代碼恰响。那我們繼續(xù)往后看趣钱,在第44行涌献,如果target等于null胚宦,就會(huì)進(jìn)入到該條件判斷內(nèi)部,這里一般情況下target都會(huì)是null燕垃,因此會(huì)在第50行調(diào)用super.dispatchTouchEvent(ev)枢劝。這句代碼會(huì)調(diào)用到哪里呢?當(dāng)然是View中的dispatchTouchEvent方法了卜壕,因?yàn)閂iewGroup的父類(lèi)就是View您旁。之后的處理邏輯又和前面所說(shuō)的是一樣的了,也因此MyLayout中注冊(cè)的onTouch方法會(huì)得到執(zhí)行轴捎。之后的代碼在一般情況下是走不到的了鹤盒,我們也就不再繼續(xù)往下分析。
再看一下整個(gè)ViewGroup事件分發(fā)過(guò)程的流程圖吧侦副,相信可以幫助大家更好地去理解:
現(xiàn)在整個(gè)ViewGroup的事件分發(fā)流程的分析也就到此結(jié)束了侦锯,我們最后再來(lái)簡(jiǎn)單梳理一下吧。
1. Android事件分發(fā)是先傳遞到ViewGroup秦驯,再由ViewGroup傳遞到View的尺碰。
2. 在ViewGroup中可以通過(guò)onInterceptTouchEvent方法對(duì)事件傳遞進(jìn)行攔截,onInterceptTouchEvent方法返回true代表不允許事件繼續(xù)向子View傳遞译隘,返回false代表不對(duì)事件進(jìn)行攔截亲桥,默認(rèn)返回false。
3. 子View中如果將傳遞的事件消費(fèi)掉固耘,ViewGroup中將無(wú)法接收到任何事件题篷。
好了,Android事件分發(fā)機(jī)制完全解析到此全部結(jié)束厅目,結(jié)合上下兩篇番枚,相信大家對(duì)事件分發(fā)的理解已經(jīng)非常深刻了偿枕。