一榔组、 ? ? ?Android分發(fā)機(jī)制概述:
Android如此受歡迎,就在于其優(yōu)秀的交互性药有,這其中毅戈,Android優(yōu)秀的事件分發(fā)機(jī)制功不可沒苹丸。那么,作為一個優(yōu)秀的程序員苇经,要想做一個具有良好交互性的應(yīng)用赘理,必須透徹理解Android的事件分發(fā)機(jī)制。
要想充分理解android的分發(fā)機(jī)制扇单,需要先對以下幾個知識點(diǎn)有所了解:
① ? View和ViewGroup什么商模?
② ? 事件
③ ? View 事件的分發(fā)機(jī)制
④ ? ViewGroup事件的分發(fā)機(jī)制
下面,就讓我們沿著大致方針蜘澜,開始事件分發(fā)的探究之旅吧……
二施流、 ? ? ?View和ViewGroup:
Android的UI界面是由View和ViewGroup及其派生類組合而成的。其中鄙信,View是所有UI組件的基類瞪醋,而ViewGroup是容納這些組件的容器,其本身也是從View派生出來的装诡,也就是說ViewGroup的父類就是View银受。
```
android.view.View
?android.view.ViewGroup
```
我們知道Button、ImageView鸦采、TextView等控件繼承View來實現(xiàn)的宾巍。
RelativeLayout、LinearLayout赖淤、FrameLayout等布局都是繼承父類ViewGroup來實現(xiàn)的蜀漆。
事件:
當(dāng)手指觸摸到View或ViewGroup派生的控件后,將會觸發(fā)一系列的觸發(fā)響應(yīng)事件咱旱。
onTouchEvent确丢、onClick、onLongClick等吐限。
每個View都有自己處理事件的回調(diào)方法鲜侥,開發(fā)人員只需要重寫這些回調(diào)方法,就可以實現(xiàn)需要的響應(yīng)事件诸典。
而事件通常重要的有如下三種:
MotionEvent.ACTION_DOWN ?按下View描函,是所有事件的開始
MotionEvent.ACTION_MOVE ? 滑動事件
MotionEvent.ACTION_UP ? ? ? 與down對應(yīng),表示離開屏幕
事件的響應(yīng)原理:
在android開發(fā)設(shè)計模式中狐粱,最廣泛應(yīng)用的就是監(jiān)聽舀寓、回調(diào),進(jìn)而形成了事件響應(yīng)的過程肌蜻。
以Button的OnClick為例互墓,因為Button也是一個View,所以它也擁有View父類的方法蒋搜。
View中源碼如下:
```
/**定義接口成員變量*/
protected OnClickListener mOnClickListener;
public interface OnClickListener {
? ? void onClick(View v);
}
public void setOnClickListener(OnClickListener l) {
? ? if (!isClickable()) {
? ? ? ? setClickable(true);
? ? }
? ? mOnClickListener = l;
}
public boolean performClick() {
? ? sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
? ? if (mOnClickListener != null) {
? ? ? ? playSoundEffect(SoundEffectConstants.CLICK);
? ? ? ? mOnClickListener.onClick(this);
? ? ? ? return true;
? ? }
? ? return false;
}
/**觸摸屏幕后篡撵,實現(xiàn)并調(diào)用的方法*/
public boolean onTouchEvent(MotionEvent event) {
…..
? ? if (mPerformClick == null) {
? ? ? ? mPerformClick = new PerformClick();
? ? }
? ? if (!post(mPerformClick)) {
? ? ? ? performClick();
? ? }
…..
}
```
以上是View源碼中關(guān)鍵代碼行判莉,以Button為例,假設(shè)在一個布局控件上添加一個按鈕育谬,并實現(xiàn)它的OnClick事件券盅,需要如下步驟:
1、 ? ? ? ? OnClickListener類是一個當(dāng)控件被點(diǎn)擊后進(jìn)行回調(diào)的一個接口膛檀,它完成被點(diǎn)擊后的回調(diào)通知锰镀。
2、 ? ? ? ? 創(chuàng)建一個按鈕Button宿刮,并設(shè)置監(jiān)聽事件互站,對這個Button進(jìn)行setOnClickListener操作
3、 ? ? ? ? 當(dāng)手指觸摸到Button按鈕僵缺,通過一系列方法(之后將會詳細(xì)講解胡桃,這里暫時忽略),觸發(fā)并執(zhí)行到onTouchEvent方法
調(diào)用mPerformClick方法磕潮,
在mPerformClick方法中 {
判斷注冊的mOnClickListener是否為空 {
若不為空翠胰,它就會回調(diào)之前注冊的onClick方法,進(jìn)而執(zhí)行用戶自定義代碼自脯。
}
事件響應(yīng)機(jī)制之景,簡單來說上面的例子就已經(jīng)基本上詮釋了
注冊一個監(jiān)聽對象
實現(xiàn)監(jiān)聽對象的監(jiān)聽事件
當(dāng)某一觸發(fā)事件到來,在觸發(fā)事件中通過注冊過的監(jiān)聽對象膏潮,回調(diào)注冊對象的響應(yīng)事件锻狗,來完成用戶自定義實現(xiàn)。
但凡明白了這一個簡單的事件響應(yīng)的過程焕参,就離事件驅(qū)動開發(fā)整個過程就不遠(yuǎn)了轻纪,大道至簡,請完全理解了這個例子叠纷,再繼續(xù)之后的學(xué)習(xí)刻帚,事半功倍。
三涩嚣、 ? ? ?View事件的分發(fā)機(jī)制:
通過上面的例子崇众,我們初步的接觸了View的事件分發(fā)機(jī)制,再進(jìn)一步了解航厚。首先顷歌,我們要熟悉dispatchTouchEvent (MotionEvent event)
onTouchEvent (MotionEvent event)
兩個函數(shù),這兩個函數(shù)都是View的函數(shù)幔睬,要理解View事件的分發(fā)機(jī)制眯漩,只要清楚這兩個函數(shù)就基本上清楚了。
在這里先提醒一句溪窒,這里的“分發(fā)”是指一個觸摸或點(diǎn)擊的事件發(fā)生坤塞,分發(fā)給當(dāng)前觸摸控件所監(jiān)聽的事件(如OnClick、onTouch等)澈蚌,進(jìn)而來決定是控件的哪個函數(shù)來響應(yīng)此次事件摹芙。
dispatchTouchEvent(MotionEvent event):
此函數(shù)負(fù)責(zé)事件的分發(fā),你只需要記住當(dāng)觸摸一個View控件宛瞄,首先會調(diào)用這個函數(shù)就行浮禾,在這個函數(shù)體里決定將事件分發(fā)給誰來處理。
onTouchEvent (MotionEvent event):
此函數(shù)負(fù)責(zé)執(zhí)行事件的處理份汗,負(fù)責(zé)處理事件盈电,主要處理
MotionEvent.ACTION_DOWN、
MotionEvent.ACTION_MOVE 杯活、
MotionEvent.ACTION_UP
這三個事件匆帚。
public boolean onTouchEvent (MotionEvent event)
參數(shù)event為手機(jī)屏幕觸摸事件封裝類的對象,其中封裝了該事件的所有信息旁钧,例如觸摸的位置吸重、觸摸的類型以及觸摸的時間等。
該對象會在用戶觸摸手機(jī)屏幕時被創(chuàng)建歪今。
那么它是如何執(zhí)行這個流程的呢嚎幸?我們還以布局上的按鈕為例,看看它是如何實現(xiàn)的寄猩。(看圖①)
圖①
我們知道嫉晶,View做為所有控件的父類,它本身定義了很多接口來監(jiān)聽觸摸在View上的事件田篇,如OnClickListener(點(diǎn)擊)替废、
OnLongClickListener(長按)、
OnTouchListener(觸摸監(jiān)聽)等斯辰,那么當(dāng)手指觸摸到View時候舶担,該響應(yīng)“點(diǎn)擊”還是”觸摸”呢,就是根據(jù)
dispatchTouchEvent
onTouchEvent
這兩個函數(shù)組合實現(xiàn)的,我們接下來的討論彬呻,僅對常用的“點(diǎn)擊OnClick”和“觸摸onTouch”衣陶,順藤摸瓜,找出主線闸氮,進(jìn)而搞清楚View的事件分發(fā)機(jī)制剪况。
對于上面的按鈕,點(diǎn)擊它一下蒲跨,我們期望2種結(jié)果译断,
第一種:它響應(yīng)一個點(diǎn)擊事件。
第二種:不響應(yīng)點(diǎn)擊事件或悲。
第一種源碼:
public class MainActivity extends Activity implements OnClickListener ,OnTouchListener{
private Button btnButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnButton=(Button) findViewById(R.id.btn);
btnButton.setOnClickListener(this);
btnButton.setOnTouchListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btn:
Log.e("View", "onClick===========>");
break;
default:
break;
}
}
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
Log.e("View", "onTouch..................................");
return false;
}
}
(圖②)
第二種源碼:
public class MainActivity extends Activity implements OnClickListener ,OnTouchListener{
private Button btnButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnButton=(Button) findViewById(R.id.btn);
btnButton.setOnClickListener(this);
btnButton.setOnTouchListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btn:
Log.e("View", "onClick===========>");
break;
default:
break;
}
}
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
Log.e("View", "onTouch..................................");
return true;
}
}
(圖③)
結(jié)果分析:
上面兩處代碼孙咪,第一種執(zhí)行了OnClick函數(shù)和OnTouch函數(shù)堪唐,第二種執(zhí)行了OnTouch函數(shù),并沒有執(zhí)行OnClick函數(shù)翎蹈,而且對兩處代碼進(jìn)行比較淮菠,發(fā)現(xiàn)只有在onTouch處返回值true和false不同。當(dāng)onTouch返回false荤堪,onClick被執(zhí)行了合陵,返回true,onClick未被執(zhí)行澄阳。
為什么會這樣呢拥知?我們只有深入源碼才能分析出來。
前面提到碎赢,觸摸一個View就會執(zhí)行dispatchTouchEvent方法去“分發(fā)”事件低剔, ?既然觸摸的是按鈕Button,那么我們就查看Button的源碼肮塞,尋找dispatchTouchEvent方法户侥,Button源碼中沒有dispatchTouchEvent方法,但知道Button繼承自TextView峦嗤,尋找TextView蕊唐,發(fā)現(xiàn)它也沒有dispatchTouchEvent方法,繼續(xù)查找TextView的父類View烁设,發(fā)現(xiàn)View有dispatchTouchEvent方法替梨,那我們就分析dispatchTouchEvent方法。
主要代碼如下:
public boolean dispatchTouchEvent(MotionEvent event) {
if (onFilterTouchEventForSecurity(event)) {
//noinspection SimplifiableIfStatement
if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED &&
mOnTouchListener.onTouch(this, event)) {
return true;
}
if (onTouchEvent(event)) {
return true;
}
}
return false;
}
分析:
先來看dispatchTouchEvent函數(shù)返回值装黑,如果返回true副瀑,表明事件被處理了,反之恋谭,表明事件未被處理糠睡。
if (onFilterTouchEventForSecurity(event))這個是事件安全過濾,與主題無關(guān)疚颊,繼續(xù)看狈孔。
if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED &&
mOnTouchListener.onTouch(this, event)) {
return true;
}
這個判定很重要,mOnTouchListener != null材义,判斷該控件是否注冊了OnTouchListener對象的監(jiān)聽均抽,(mViewFlags & ENABLED_MASK) == ENABLED,判斷當(dāng)前的控件是否能被點(diǎn)擊(比如Button默認(rèn)可以點(diǎn)擊其掂,ImageView默認(rèn)不許點(diǎn)擊油挥,看到這里就了然了),mOnTouchListener.onTouch(this, event)這個是關(guān)鍵,這個調(diào)用深寥,就是回調(diào)你注冊在這個View上的mOnTouchListener對象的onTouch方法攘乒,如果你在onTouch方法里返回false,那么這個判斷語句就跳出惋鹅,去執(zhí)行下面的程序持灰,否則,當(dāng)前2個都返回了true负饲,自定義onTouch方法也返回true,條件成立喂链,就直接返回了返十,不再執(zhí)行下面的程序。接下來椭微,if (onTouchEvent(event)) 這個判斷很重要洞坑,能否回調(diào)OnClickListener接口的onClick函數(shù)锯仪,關(guān)鍵在于此挣郭,可以肯定的是竭恬,如果上面if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED &&
mOnTouchListener.onTouch(this, event))返回true锐借,那么就不會執(zhí)行并回調(diào)OnClickListener接口的onClick函數(shù)哎迄。
接下來踏堡,我們看onTouchEvent這個函數(shù)唱矛,看它是如何響應(yīng)點(diǎn)擊事件的缺前。
主要代碼如下:
public boolean onTouchEvent(MotionEvent event) {
final int viewFlags = mViewFlags;
if ((viewFlags & ENABLED_MASK) == DISABLED) {
if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PRESSED) != 0) {
mPrivateFlags &= ~PRESSED;
refreshDrawableState();
}
// A disabled view that is clickable still consumes the touch
// events, it just doesn't respond to them.
return (((viewFlags & CLICKABLE) == CLICKABLE ||
(viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
}
if (mTouchDelegate != null) {
if (mTouchDelegate.onTouchEvent(event)) {
return true;
}
}
if (((viewFlags & CLICKABLE) == CLICKABLE ||
(viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
// take focus if we don't have it already and we should in
// touch mode.
boolean focusTaken = false;
if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
focusTaken = requestFocus();
}
if (prepressed) {
// The button is being released before we actually
// showed it as pressed. ?Make it show the pressed
// state now (before scheduling the click) to ensure
// the user sees it.
mPrivateFlags |= PRESSED;
refreshDrawableState();
}
if (!mHasPerformedLongPress) {
// This is a tap, so remove the longpress check
removeLongPressCallback();
// Only perform take click actions if we were in the pressed state
if (!focusTaken) {
// Use a Runnable and post this rather than calling
// performClick directly. This lets other visual state
// of the view update before click actions start.
if (mPerformClick == null) {
mPerformClick = new PerformClick();
}
if (!post(mPerformClick)) {
performClick();
}
}
}
if (mUnsetPressedState == null) {
mUnsetPressedState = new UnsetPressedState();
}
if (prepressed) {
postDelayed(mUnsetPressedState,
ViewConfiguration.getPressedStateDuration());
} else if (!post(mUnsetPressedState)) {
// If the post failed, unpress right now
mUnsetPressedState.run();
}
removeTapCallback();
}
break;
case MotionEvent.ACTION_DOWN:
mHasPerformedLongPress = false;
if (performButtonActionOnTouchDown(event)) {
break;
}
// Walk up the hierarchy to determine if we're inside a scrolling container.
boolean isInScrollingContainer = isInScrollingContainer();
// For views inside a scrolling container, delay the pressed feedback for
// a short period in case this is a scroll.
if (isInScrollingContainer) {
mPrivateFlags |= PREPRESSED;
if (mPendingCheckForTap == null) {
mPendingCheckForTap = new CheckForTap();
}
postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
} else {
// Not inside a scrolling container, so show the feedback right away
mPrivateFlags |= PRESSED;
refreshDrawableState();
checkForLongClick(0);
}
break;
case MotionEvent.ACTION_CANCEL:
mPrivateFlags &= ~PRESSED;
refreshDrawableState();
removeTapCallback();
break;
case MotionEvent.ACTION_MOVE:
final int x = (int) event.getX();
final int y = (int) event.getY();
// Be lenient about moving outside of buttons
if (!pointInView(x, y, mTouchSlop)) {
// 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;
}
return true;
}
return false;
}
public boolean performClick() {
sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
if (mOnClickListener != null) {
playSoundEffect(SoundEffectConstants.CLICK);
mOnClickListener.onClick(this);
return true;
}
return false;
}
代碼量太大了锅尘,不過不要緊监氢,我們通過主要代碼分析一下。
public boolean onTouchEvent(MotionEvent event) {
//控件不能被點(diǎn)擊
if ((viewFlags & ENABLED_MASK) == DISABLED) {
…
}
//委托代理別的View去實現(xiàn)
if (mTouchDelegate != null) {
if (mTouchDelegate.onTouchEvent(event)) {
return true;
}
}
//控件能夠點(diǎn)擊或者長按
if (((viewFlags & CLICKABLE) == CLICKABLE ||
(viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
switch (event.getAction()) {
//抬起事件
case MotionEvent.ACTION_UP:
…...
if (!focusTaken) {
// Use a Runnable and post this rather than calling
// performClick directly. This lets other visual state
// of the view update before click actions start.
if (mPerformClick == null) {
mPerformClick = new PerformClick();
}
if (!post(mPerformClick)) {
//這里就是去執(zhí)行回調(diào)注冊的onClick函數(shù)藤违,實現(xiàn)點(diǎn)擊
performClick();
}
}
……
break;
//按下事件
case MotionEvent.ACTION_DOWN:
……
break;
……
//移動事件
case MotionEvent.ACTION_MOVE:
……
break;
}
return true;
}
return false;
}
從上面主要代碼可以看出onTouchEvent傳參MotionEvent類型浪腐,它封裝了觸摸的活動事件,其中就有MotionEvent.ACTION_DOWN顿乒、MotionEvent.ACTION_MOVE议街、MotionEvent.ACTION_UP三個事件。我們再來看看onTouchEvent的返回值璧榄,因為onTouchEvent是在dispatchTouchEvent事件分發(fā)處理中調(diào)用的特漩,
public boolean dispatchTouchEvent(MotionEvent event) {
……
if (onTouchEvent(event)) {
return true;
}
return fasle;
}
如果onTouchEvent返回true,dispatchTouchEvent就返回true骨杂,表明事件被處理了拾稳,反之,事件未被處理腊脱。
程序的關(guān)鍵在 ?if (((viewFlags & CLICKABLE) == CLICKABLE ||
(viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE))的判斷里访得,我們發(fā)現(xiàn)無論switch的分支在什么地方跳出,返回都是true。這就表明悍抑,無論是三個事件中的哪一個鳄炉,都會返回true。
參照下圖搜骡,結(jié)合上述拂盯,不難理解View的分發(fā)機(jī)制了。
(圖④)
四记靡、 ? ? ?ViewGroup事件分發(fā)機(jī)制:
ViewGroup事件分發(fā)機(jī)制較View的稍微復(fù)雜一些谈竿,不過對View的機(jī)制只要精確的理解后,仔細(xì)看過這一節(jié)摸吠,睡幾覺起來空凸,估計也就悟出來了,學(xué)習(xí)就是這么奇怪寸痢,當(dāng)下理解不了或模糊的地方呀洲,只要腦子有印象,忽然一夜好像就懂了啼止。
先來看下面的一個簡單布局道逗,我們將通過例子,了解ViewGroup+View的android事件處理機(jī)制献烦。
(圖⑤)
上圖由:黑色為線性布局LinearLayout滓窍,紫色為相對布局RelativeLayout,按鈕Button三部分組成巩那。RelativeLayout為LinearLayout的子布局贰您,Button為RelativeLayout的子布局。以下RelativeLayout簡稱(R)拢操,LinearLayout簡稱(L)锦亦,Button簡稱(B)。
經(jīng)過前面講解令境,我們首先知道這樣兩件事情杠园。
1、(R)和(L)的父類是ViewGroup舔庶,(B)的父類是View抛蚁。
2、dispatchTouchEvent這個函數(shù)很重要惕橙,不論是ViewGroup還是View瞧甩,都由它來處理事件的消費(fèi)和傳遞。
下面弥鹦,我們通過橫向和縱向兩個維度肚逸,通過源碼和圖解的方式爷辙,充分理解事件的傳遞機(jī)制。
先來看整體的事件傳遞過程:
(圖⑥)
當(dāng)手指點(diǎn)擊按鈕B時朦促,事件傳遞的順序是從底向上傳遞的膝晾,也就是按照L->R->B的順序由下往上逐層傳遞,響應(yīng)正好相反务冕,是自上而下血当。
L首先接收到點(diǎn)擊事件,L的父類是ViewGroup類禀忆,并將事件傳遞給dispatchTouchEvent方法臊旭,dispatchTouchEvent函數(shù)中判斷該控件L是否重載了onInterceptTouchEvent方法進(jìn)行事件攔截,onInterceptTouchEvent默認(rèn)返回false不攔截箩退,那么dispatchTouchEvent方法將事件傳遞給R去處理(進(jìn)入第2流程處理)离熏,如果返回true表示當(dāng)前L控件攔截了事件向其它控件的傳遞,交給它自己父類View的dispatchTouchEvent去處理乏德,在父方法的dispatchTouchEvent中,將會按照前面講的View的事件處理機(jī)制去判斷吠昭,比如判斷L是否重載了onTouch方法喊括,是否可點(diǎn)擊,是否做了監(jiān)聽等事件矢棚。
R也是ViewGroup的子類郑什,因此與第1流程基本相似,如果onInterceptTouchEvent返回了false蒲肋,表示事件將不攔截繼續(xù)傳遞給B蘑拯。
B是View的子類,它沒有onInterceptTouchEvent方法兜粘,直接交給自己父類View的dispatchTouchEvent去處理申窘,流程同不再敷述。
總結(jié):
onInterceptTouchEvent只有ViewGroup才有孔轴,當(dāng)一個控件是繼承自ViewGroup而來的剃法,那么它就可能會有子控件,因此路鹰,才有可能傳遞給子控件贷洲,而繼承自View的控件,不會有子控件晋柱,也就沒有onInterceptTouchEvent函數(shù)了优构。
通過dispatchTouchEvent分發(fā)的控件返回值True和false,表示當(dāng)前控件是否消費(fèi)了傳遞過來的事件雁竞,如果消費(fèi)了钦椭,返回True,反之false。消費(fèi)了玉凯,就不再繼續(xù)傳遞了势腮,沒有消費(fèi),如果有子控件將繼續(xù)傳遞漫仆。
啰嗦點(diǎn)捎拯,如果想再深層次了解一下,再次從源碼ViewGroup來分析一個L控件的事件傳遞過程盲厌,請看下圖:
(圖⑦)
結(jié)合上面的圖例署照,下面列出ViewGroup源碼來分析一下,我們只需要分析ViewGroup的dispatchTouchEvent吗浩、onInterceptTouchEvent建芙、dispatchTransformedTouchEvent三個方法即可。
public boolean dispatchTouchEvent(MotionEvent ev) {
if (mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
}
boolean handled = false;
if (onFilterTouchEventForSecurity(ev)) {
final int action = ev.getAction();
final int actionMasked = action & MotionEvent.ACTION_MASK;
// Handle an initial down.
if (actionMasked == MotionEvent.ACTION_DOWN) {
// Throw away all previous state when starting a new touch gesture.
// The framework may have dropped the up or cancel event for the previous gesture
// due to an app switch, ANR, or some other state change.
cancelAndClearTouchTargets(ev);
resetTouchState();
}
// Check for interception.
final boolean intercepted;
if (actionMasked == MotionEvent.ACTION_DOWN
|| mFirstTouchTarget != null) {
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
if (!disallowIntercept) {
intercepted = onInterceptTouchEvent(ev);
ev.setAction(action); // restore action in case it was changed
} else {
intercepted = false;
}
} else {
// There are no touch targets and this action is not an initial down
// so this view group continues to intercept touches.
intercepted = true;
}
// Check for cancelation.
final boolean canceled = resetCancelNextUpFlag(this)
|| actionMasked == MotionEvent.ACTION_CANCEL;
// Update list of touch targets for pointer down, if needed.
final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;
TouchTarget newTouchTarget = null;
boolean alreadyDispatchedToNewTouchTarget = false;
if (!canceled && !intercepted) {
if (actionMasked == MotionEvent.ACTION_DOWN
|| (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)
|| actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
final int actionIndex = ev.getActionIndex(); // always 0 for down
final int idBitsToAssign = split ? 1 << ev.getPointerId(actionIndex)
: TouchTarget.ALL_POINTER_IDS;
// Clean up earlier touch targets for this pointer id in case they
// have become out of sync.
removePointersFromTouchTargets(idBitsToAssign);
final int childrenCount = mChildrenCount;
if (childrenCount != 0) {
// Find a child that can receive the event.
// Scan children from front to back.
final View[] children = mChildren;
final float x = ev.getX(actionIndex);
final float y = ev.getY(actionIndex);
for (int i = childrenCount - 1; i >= 0; i--) {
final View child = children[i];
if (!canViewReceivePointerEvents(child)
|| !isTransformedTouchPointInView(x, y, child, null)) {
continue;
}
newTouchTarget = getTouchTarget(child);
if (newTouchTarget != null) {
// Child is already receiving touch within its bounds.
// Give it the new pointer in addition to the ones it is handling.
newTouchTarget.pointerIdBits |= idBitsToAssign;
break;
}
resetCancelNextUpFlag(child);
if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
// Child wants to receive touch within its bounds.
mLastTouchDownTime = ev.getDownTime();
mLastTouchDownIndex = i;
mLastTouchDownX = ev.getX();
mLastTouchDownY = ev.getY();
newTouchTarget = addTouchTarget(child, idBitsToAssign);
alreadyDispatchedToNewTouchTarget = true;
break;
}
}
}
if (newTouchTarget == null && mFirstTouchTarget != null) {
// Did not find a child to receive the event.
// Assign the pointer to the least recently added target.
newTouchTarget = mFirstTouchTarget;
while (newTouchTarget.next != null) {
newTouchTarget = newTouchTarget.next;
}
newTouchTarget.pointerIdBits |= idBitsToAssign;
}
}
}
// Dispatch to touch targets.
if (mFirstTouchTarget == null) {
// No touch targets so treat this as an ordinary view.
handled = dispatchTransformedTouchEvent(ev, canceled, null,
TouchTarget.ALL_POINTER_IDS);
} else {
// Dispatch to touch targets, excluding the new touch target if we already
// dispatched to it. ?Cancel touch targets if necessary.
TouchTarget predecessor = null;
TouchTarget target = mFirstTouchTarget;
while (target != null) {
final TouchTarget next = target.next;
if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
handled = true;
} else {
final boolean cancelChild = resetCancelNextUpFlag(target.child)
|| intercepted;
if (dispatchTransformedTouchEvent(ev, cancelChild,
target.child, target.pointerIdBits)) {
handled = true;
}
if (cancelChild) {
if (predecessor == null) {
mFirstTouchTarget = next;
} else {
predecessor.next = next;
}
target.recycle();
target = next;
continue;
}
}
predecessor = target;
target = next;
}
}
// Update list of touch targets for pointer up or cancel, if needed.
if (canceled
|| actionMasked == MotionEvent.ACTION_UP
|| actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
resetTouchState();
} else if (split && actionMasked == MotionEvent.ACTION_POINTER_UP) {
final int actionIndex = ev.getActionIndex();
final int idBitsToRemove = 1 << ev.getPointerId(actionIndex);
removePointersFromTouchTargets(idBitsToRemove);
}
}
if (!handled && mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onUnhandledEvent(ev, 1);
}
return handled;
}
public boolean onInterceptTouchEvent(MotionEvent ev) {
return false;
}
private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
View child, int desiredPointerIdBits) {
final boolean handled;
// Canceling motions is a special case. ?We don't need to perform any transformations
// or filtering. ?The important part is the action, not the contents.
final int oldAction = event.getAction();
if (cancel || oldAction == MotionEvent.ACTION_CANCEL) {
event.setAction(MotionEvent.ACTION_CANCEL);
if (child == null) {
handled = super.dispatchTouchEvent(event);
} else {
handled = child.dispatchTouchEvent(event);
}
event.setAction(oldAction);
return handled;
}
// Calculate the number of pointers to deliver.
final int oldPointerIdBits = event.getPointerIdBits();
final int newPointerIdBits = oldPointerIdBits & desiredPointerIdBits;
// If for some reason we ended up in an inconsistent state where it looks like we
// might produce a motion event with no pointers in it, then drop the event.
if (newPointerIdBits == 0) {
return false;
}
// If the number of pointers is the same and we don't need to perform any fancy
// irreversible transformations, then we can reuse the motion event for this
// dispatch as long as we are careful to revert any changes we make.
// Otherwise we need to make a copy.
final MotionEvent transformedEvent;
if (newPointerIdBits == oldPointerIdBits) {
if (child == null || child.hasIdentityMatrix()) {
if (child == null) {
handled = super.dispatchTouchEvent(event);
} else {
final float offsetX = mScrollX - child.mLeft;
final float offsetY = mScrollY - child.mTop;
event.offsetLocation(offsetX, offsetY);
handled = child.dispatchTouchEvent(event);
event.offsetLocation(-offsetX, -offsetY);
}
return handled;
}
transformedEvent = MotionEvent.obtain(event);
} else {
transformedEvent = event.split(newPointerIdBits);
}
// Perform any necessary transformations and dispatch.
if (child == null) {
handled = super.dispatchTouchEvent(transformedEvent);
} else {
final float offsetX = mScrollX - child.mLeft;
final float offsetY = mScrollY - child.mTop;
transformedEvent.offsetLocation(offsetX, offsetY);
if (! child.hasIdentityMatrix()) {
transformedEvent.transform(child.getInverseMatrix());
}
handled = child.dispatchTouchEvent(transformedEvent);
}
// Done.
transformedEvent.recycle();
return handled;
}
代碼量比較大懂扼,我們先概述一下各個函數(shù)的主要作用禁荸。
dispatchTouchEvent主要用來分發(fā)事件,函數(shù)主要作用是來決定當(dāng)前的事件是交由自己消費(fèi)處理阀湿,還是交由子控件處理赶熟。
onInterceptTouchEvent主要來決定當(dāng)前控件是否需要攔截傳遞給子控件,如果返回True表示該控件攔截陷嘴,并交由自己父類的dispatchTouchEvent處理消費(fèi)映砖,如果返回false表示不攔截,允許傳遞給子控件處理灾挨。
dispatchTransformedTouchEvent主要根據(jù)傳來的子控件邑退,決定是自身處理消費(fèi),還是交由子控件處理消費(fèi)劳澄。
我們主要來分析一下dispatchTouchEvent函數(shù):
if (actionMasked == MotionEvent.ACTION_DOWN
|| mFirstTouchTarget != null) {
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
if (!disallowIntercept) {
intercepted = onInterceptTouchEvent(ev);
ev.setAction(action); // restore action in case it was changed
} else {
intercepted = false;
}
} else {
// There are no touch targets and this action is not an initial down
// so this view group continues to intercept touches.
intercepted = true;
}
這段代碼地技,如果當(dāng)前傳遞的事件是Down(按下)或者當(dāng)前觸摸鏈表不為空,那么它調(diào)用onInterceptTouchEvent函數(shù)秒拔,判斷是否進(jìn)行事件攔截處理乓土,通過返回值來決定intercepted變量的值。
接下來if (!canceled && !intercepted){} 這個括號內(nèi)的代碼需要注意了溯警,只有當(dāng)intercepted返回值為false的時候趣苏,才滿足這個條件進(jìn)入代碼段。因此梯轻,我們結(jié)合onInterceptTouchEvent源碼食磕,發(fā)現(xiàn)它默認(rèn)值返回的是false,也就說如果你不重載onInterceptTouchEvent方法并令其返回True喳挑,它一定是返回false彬伦,并能夠執(zhí)行花括號內(nèi)的代碼滔悉。
我們分析一下花括號中的代碼,if (actionMasked == MotionEvent.ACTION_DOWN
|| (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)
|| actionMasked == MotionEvent.ACTION_HOVER_MOVE) {}判斷當(dāng)前的事件是否是ACTION_DOWN单绑、ACTION_POINTER_DOWN(多點(diǎn)觸摸)回官、ACTION_HOVER_MOVE(懸停),如果是搂橙,執(zhí)行花括號內(nèi)代碼歉提,
final int childrenCount = mChildrenCount;
if (childrenCount != 0) {}判斷當(dāng)前控件是否有子控件,如果大于0区转,執(zhí)行花括號內(nèi)代碼苔巨,
for (int i = childrenCount - 1; i >= 0; i--)遍歷子控件,
if (!canViewReceivePointerEvents(child)
判斷當(dāng)前的down废离、POINTER_DOWN侄泽、HOVER_MOVE三個事件的坐標(biāo)點(diǎn)是否落在了子控件上,如果落在子控件上蜻韭,
if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign))
通過dispatchTransformedTouchEvent傳遞事件悼尾,交由子控件判斷是否傳遞或自己消費(fèi)處理。如果dispatchTransformedTouchEvent返回true肖方,表示子控件已消費(fèi)處理闺魏,并添加此子控件View到觸摸鏈表,并放置鏈表頭窥妇,并結(jié)束遍歷子控件舷胜。newTouchTarget = addTouchTarget(child, idBitsToAssign);false表示未處理娩践。
接著分析
if (mFirstTouchTarget == null) {
handled = dispatchTransformedTouchEvent(ev, canceled, null,
TouchTarget.ALL_POINTER_IDS);
} else {
……
}
mFirstTouchTarget什么時候為空呢活翩?從前面的代碼可以看到,如果onInterceptTouchEvent返回為false(也就是不攔截)翻伺,mFirstTouchTarget就為空材泄,直接交給自己父View執(zhí)行dispatchTouchEvent去了。如果mFirstTouchTarget不為空吨岭,它就取出觸摸鏈表拉宗,逐個遍歷判斷處理,如果前面比如Down事件處理過了辣辫,就不再處理了旦事。