Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android觸摸事件傳遞機制全解析:從WMS一路走到View樹

編輯:關於 Android 開發

Android觸摸事件傳遞機制全解析:從WMS一路走到View樹

轉眼快一年沒更新部落格了,工作一忙起來就很難擠出時間寫文章。由於目前正從事Android相關開發,往後的文章也會更多地聚焦在這塊領域。

這篇要從源碼層面帶大家梳理Touch事件的傳遞機制,我分析的源碼基於Android 4.4。分析源碼光看是不夠的,一定要親手去跟、邊跟邊思考,所以下一篇會準備一個Demo來詳細追蹤源碼走向。

先來看看Android中事件的分類:

1、鍵盤事件:主要指按下虛擬鍵盤某個按鍵,或機身實體按鍵時產生的事件。

2、鼠標事件:Android 4.0之後增加了對鼠標事件的監控,如ACTION_HOVER_ENTER。

3、觸摸屏事件:凡是觸摸屏幕產生的事件都屬於此類,包括單點觸控、多點觸控、軌跡球事件等。

這裡主要講解單點觸控事件,也就是Touch事件的傳遞。先來看完整傳遞過程:

1、首先要明白,Android中Touch事件的分發分為服務端和應用端。Server端由WindowManagerService(WMS,視窗管理服務)負責採集和分發;client端則由ViewRootImpl(內部有個mView變量指向View樹的根,負責控制View樹的UI繪製和事件消息分發)負責分發。

2、WMS啟動之後,經過逐層呼叫,會在native層啟動兩個線程:InputReaderThread和InputDispatchThread,前者負責讀取輸入事件,後者負責分發輸入事件。輸入事件經過native層的層層傳遞,最終會傳到Java層的ViewRootImpl,呼叫ViewPostImeInputStage(ViewRootImpl的內部類)中的各個方法來分發不同事件,而Touch事件是在processPointerEvent方法中分發的。

3、processPointerEvent方法中呼叫mView.dispatchPointerEvent(event),這裡的mView就是建立視窗後透過root.setView傳進來的DecorView。dispatchPointerEvent會對event進行判斷,如果是Touch事件,就呼叫dispatchTouchEvent把事件分發給DecorView,這樣Touch事件就傳進了View樹中。

Touch事件從WMS到ViewRootImpl的傳遞

下面這張圖展示了Touch事件從WMS(server端)傳遞到ViewRootImpl(client端)的流程(Android 4.4中InputManager變成了InputManagerService,ViewRoot變成了ViewRootImpl):

這裡要特別注意,Touch事件從server端傳到client端採用的IPC方式並不是Binder,而是共享內存和管道。之所以不用Binder,應該是共享內存效率更高;而管道(注意,是兩個管道,分別負責不同方向的讀和寫)只負責通知是否有事件發生,傳遞的只是一個很簡單的字符串,因此不會太多地影響IPC效率。

上圖中只有WMS、ViewRootImpl、InputManagerService、InputQueue是在Framework層實現的,其他部分都在native層實現。native層程式碼我沒細看,參考了一些網路資料和公司在內部的分享,把整個流程串了起來,如果有充足時間可以深入研究。

在server端,InputReader和InputDispatcher是native層的兩個線程:前者不斷從EventHub讀取事件(包括所有事件,會對不同事件做判斷處理),後者則不斷分發InputReader讀取到的事件。實際的分發操作在InputPublish中進行,它內部保存著一個指向server端InputChannel端的指針,和一個指向ShareMemory(共享內存)的指針。當有事件要分發時,它會把事件寫入ShareMemory,並傳遞一個特定字符串給InputChannel,由InputChannel把該字符串寫入管道。在client端,一旦InputChannel從管道讀取到有事件分發過來,便通知InputConsumer從ShareMemory讀取具體事件,並傳到Framework層的InputQueue中。同樣,事件消費完畢後,client端會透過管道告訴server端事件已消費完畢,流程與上面類似。

另外順帶說一下這裡的兩個InputChannel。它們在native層,各自在Framework層有一個對應的InputChannel類。client端的InputChannel是在ViewRootImpl的setView中new出來的,但未做任何初始化操作(真正的初始化和server端一起在WMS中執行),也就是構造方法裡是空的:

 // Schedule the first layout -before- adding to the window // manager, to make sure we do the relayout before receiving // any other events from the system. requestLayout(); if ((mWindowAttributes.inputFeatures & WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) { mInputChannel = new InputChannel(); }

server端的InputChannel雖然在server端建立,但其建立過程是在client端發起的。ViewRootImpl中有server端Session的代理,同樣在setView方法中,透過Session代理執行server端Session的addToDisplay方法,該方法接收了client端的InputChannel:

 mOrigWindowType = mWindowAttributes.type; mAttachInfo.mRecomputeGlobalAttributes = true; collectViewAttributes(); res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes, getHostVisibility(), mDisplay.getDisplayId(), mAttachInfo.mContentInsets, mInputChannel);

addToDisplay方法在Session類中,它會呼叫WindowManagerService的addWindow方法,兩個InputChannel的初始化操作都在這裡進行:

 if (outInputChannel != null && (attrs.inputFeatures & WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) { String name = win.makeInputChannelName(); InputChannel[] inputChannels = InputChannel.openInputChannelPair(name); win.setInputChannel(inputChannels[0]); inputChannels[1].transferTo(outInputChannel); mInputManager.registerInputChannel(win.mInputChannel, win.mInputWindowHandle); }

這裡的InputChannel.openInputChannelPair方法會在native層建立兩個InputChannel,並返回對應的Framework層InputChannel的兩個物件,保存在inputChannels陣列中,其中一個保留在server端,一個透過transferTo方法返回client端。openInputChannelPair和transferTo方法內部都是直接呼叫native方法。

說了這麼多,其實就是一套Binder機制,關於Binder機制大家可自行搜索,入門資料還是挺多的。這裡我根據源碼畫了兩份ViewRootImpl和WMS之間透過Binder進行IPC的序列圖,有興趣的可以自行研究,只要搞懂Binder機制,這部分程式碼就不難理解。

ViewRootImpl到WMS的連接,透過WMS提供給ViewRootImpl的IWindowSession成員(也就是Session在本地的代理)完成:

WMS到ViewRootImpl的連接,則透過ViewRootImpl提供給WMS的IWindow(ViewRootImpl的內部類)完成:

Touch事件在View樹中的分發

當Touch事件傳到ViewRootImpl後,就會在View樹中分發。要了解這部分,先得了解View樹的建立(這部分又能單獨寫一篇了,這裡不再詳述)。View樹建立完成後的結構是這樣的:

View樹的根View永遠是DecorView,它繼承自FrameLayout,內部會有一個LinearLayout,根據Window Feather的不同,LinearLayout內部的布局也不同,其中每種不同布局的xml內都有一個id為content的FrameLayout,這就是我們在自己的布局所attach的父容器。

Touch事件的傳遞自然先從ViewRootImpl傳到DecorView,因此我們從DecorView入手分析。開始之前,先梳理幾個基礎知識:

1、一般情況下,每個Touch事件總是以ACTION_DOWN開始,中間穿插著一些ACTION_MOVE(取決於是否有手勢移動),最後以ACTION_UP結束,中間還會有onTouch、Click、LongClick等事件。

2、事件分發過程涉及對MotionEvent的三種處理操作:

分發操作:dispatchTouchEvent方法,後兩個方法都在其中被呼叫。

攔截操作:onInterceptTouchEvent方法(ViewGroup)。

消費操作:onTouchEvent方法和OnTouchListener的onTouch方法,其中onTouch優先級高於onTouchEvent,若onTouch返回true,則不會呼叫onTouchEvent。

3、dispatchTouchEvent分發Touch事件是自頂向下,而onTouchEvent消費事件是自底向上,onTouchEvent和onInterceptTouchEvent都在dispatchTouchEvent中被呼叫。

下面正式進入分析。先看DecorView(PhoneWindow的內部類)的dispatchTouchEvent方法:

 @Override public boolean dispatchTouchEvent(MotionEvent ev) { final Callback cb = getCallback(); return cb != null && !isDestroyed() && mFeatureId < 0 ? cb.dispatchTouchEvent(ev) : super.dispatchTouchEvent(ev); }

這裡的cb就是當前的Activity。Activity實現了Window.Callback介面,同時在Activity的attach方法中,建立PhoneWindow後呼叫了mWindow.setCallback(this),把PhoneWindow中的callback設為當前Activity,因此cb.dispatchTouchEvent就是Activity的dispatchTouchEvent方法。如果前面三個條件同時成立(一般成立),則呼叫Activity的dispatchTouchEvent進行分發,否則直接呼叫super.dispatchTouchEvent,也就是FrameLayout的dispatchTouchEvent。其實即使呼叫了Activity的dispatchTouchEvent,最終還是會呼叫到super.dispatchTouchEvent,我們繼續看Activity的dispatchTouchEvent:

 public boolean dispatchTouchEvent(MotionEvent ev) { if (ev.getAction() == MotionEvent.ACTION_DOWN) { onUserInteraction(); } if (getWindow().superDispatchTouchEvent(ev)) { return true; } return onTouchEvent(ev); }

前面if分支不用管,這裡會呼叫PhoneWindow的superDispatchTouchEvent方法:

 @Override public boolean superDispatchTouchEvent(MotionEvent event) { return mDecor.superDispatchTouchEvent(event); }

接著呼叫DecorView的superDispatchTouchEvent方法:

 public boolean superDispatchTouchEvent(MotionEvent event) { return super.dispatchTouchEvent(event); }

最終還是呼叫DecorView的super.dispatchTouchEvent,也就是說,無論怎樣,DecorView的dispatchTouchEvent最終都會呼叫到其父類FrameLayout的dispatchTouchEvent方法,而FrameLayout中找不到dispatchTouchEvent,所以會執行ViewGroup的dispatchTouchEvent方法。如果它返回true,說明後面有view消費了事件,就返回true,不再執行自身的onTouchEvent;否則說明沒有view消費,會一路回傳到Activity,然後呼叫自己的onTouchEvent,其實現很簡單:

 public boolean onTouchEvent(MotionEvent event) { if (mWindow.shouldCloseOnTouch(this, event)) { finish(); return true; } return false; }

先呼叫mWindow.shouldCloseOnTouch判斷是否需要關閉視窗,如果是則finish掉該Activity並返回true,否則返回false。一般情況下返回false,那什麼時候會返回true呢?來看Window類中的shouldCloseOnTouch方法:

 public boolean shouldCloseOnTouch(Context context, MotionEvent event) { if (mCloseOnTouchOutside && event.getAction() == MotionEvent.ACTION_DOWN && isOutOfBounds(context, event) && peekDecorView() != null) { return true; } return false; }

大致意思是:如果設置了mCloseOnTouchOutside屬性為true(對應xml中的android:windowCloseOnTouchOutside),且當前事件為down事件,且down事件發生在該Activity範圍之外,並且DecorView不為null,就返回true。很明顯,dialog形式的Activity可能會發生這種情況。

下面重點來看ViewGroup中的dispatchTouchEvent方法:

 public boolean dispatchTouchEvent(MotionEvent ev) { //調試用的 if (mInputEventConsistencyVerifier != null) { mInputEventConsistencyVerifier.onTouchEvent(ev, 1); } //handled為返回值,表示是否有view消費了該事件。 boolean handled = false; //是否要過濾掉該Touch事件,大致是這個意思 if (onFilterTouchEventForSecurity(ev)) { final int action = ev.getAction(); final int actionMasked = action & MotionEvent.ACTION_MASK; if (actionMasked == MotionEvent.ACTION_DOWN) { //由於down事件代表一個系列事件的開始,因此如果是down事件, //1、就清空掉以前消費事件的目標view,這裡主要指清空掉mFirstTouchTarget鏈表(保存接受Touch事件的單鏈表,這點在後面的代碼中會看到),並將mFirstTouchTarget置為null; //2、重置觸摸狀態,重置了disallowIntercept對應的標志位,該變量的值決定了onInterceptTouchEvent方法是否有效,這點後面我們會看到;還有就是重置來View的mPrivateFlags標志位,這個沒去了解具體是干嘛用的。 一般在發生app的切換,或者ANR等情況時,代碼會走到這裡,這一點源碼的注釋裡也有。 cancelAndClearTouchTargets(ev); resetTouchState(); } // 標記是否要攔截該Touch事件,true表示攔截,false表示不攔截 final boolean intercepted; //如果當前事件為down事件,或者可接受Touch事件的鏈表不為空,就執行if語句裡的邏輯。這裡注意, //1、由於down事件是一個完整事件序列的的起點,因此當發生down事件時,邏輯走到這裡,還沒有找到消費down事件的view,因此mFirstTouchTarget為null, //2、而對後面的move和up事件,如果前面的down事件被某個view消費掉了,則mFirstTouchTarget不為null。 上面兩種情況都會使代碼進入if分支中來。 if (actionMasked == MotionEvent.ACTION_DOWN || mFirstTouchTarget != null) { //是否不允許攔截,默認為false,也就是允許該方法可以通過 requestDisallowInterceptTouchEvent方法來設置 final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0; // 如果允許攔截,則onInterceptTouchEvent有效,根據我們覆寫的該方法的返回值來判斷是否攔截,否則,onInterceptTouchEvent無效,不對該事件進行攔截。 if (!disallowIntercept) { intercepted = onInterceptTouchEvent(ev); ev.setAction(action); // restore action in case it was changed } else { intercepted = false; } } else { // 如果當前事件不是down事件,且之前在分發down事件的時候沒有找到消費down事件的目標view,也即mFirstTouchTarget為null,則直接攔截該事件。 intercepted = true; } // 檢查當前事件是否被取消 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; //保存消費事件的目標View所對應的 TouchTarget對象 TouchTarget newTouchTarget = null; //事件是否已經分發到了目標View中。 boolean alreadyDispatchedToNewTouchTarget = false; // 如果沒有被取消,並且沒有被攔截,就分發該事件,注意只有down事件才會走到這裡去分發,對於move和up事件,則會跳過這裡,直接從 mFirstTouchTarget鏈表中找到之前消耗down事件的目標View,直接將move和up事件非法給它,後面的代碼中我們會分析到。 if (!canceled && !intercepted) { //只有down事件會走到這裡 if (actionMasked == MotionEvent.ACTION_DOWN || (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN) || actionMasked == MotionEvent.ACTION_HOVER_MOVE) { //Touch事件的index,對於單點觸控,一直為0,這裡不用深究 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); //該ViewGroup中子View的個數 final int childrenCount = mChildrenCount; if (newTouchTarget == null && childrenCount != 0) { //當前事件發生的位置 final float x = ev.getX(actionIndex); final float y = ev.getY(actionIndex); //保存該ViewGroup中子View final View[] children = mChildren; final boolean customOrder = isChildrenDrawingOrderEnabled(); //遍歷子View,找到能消費該down事件的子View,對於類型為ViewGroup的子View,在分發的時候,會遞歸調用到它的dispatchTouchEvent方法繼續進行分發。 for (int i = childrenCount - 1; i >= 0; i--) { final int childIndex = customOrder ? getChildDrawingOrder(childrenCount, i) : i; final View child = children[childIndex]; //如果當前子View可以消費該down事件,並且該down事件發生的位置在當前子View的范圍內,則繼續執行,將down事件分發給它,否則,continue判斷下一個子View可否接受該down事件。 if (!canViewReceivePointerEvents(child) || !isTransformedTouchPointInView(x, y, child, null)) { continue; } //判斷該能接受該down事件的child是否已經在mFirstTouchTarget鏈表中,如果在的話,說明child已經消費掉了該down事件,直接跳出循環。我在寫demo跟代碼時,沒有一次走到這裡的,暫時不是很清楚,怎樣的場景下,代碼會執行到這裡的break。 newTouchTarget = getTouchTarget(child); if (newTouchTarget != null) { newTouchTarget.pointerIdBits |= idBitsToAssign; break; } resetCancelNextUpFlag(child); //如果該child還沒有消費掉該down事件,就直接調用dispatchTransformedTouchEvent方法將該down事件傳遞給該child,該方法裡面會調用到child的dispatchTouchEvent方法,如果該方法返回true,則說明child消費掉了該down事件,那麼就執行if語句裡的邏輯,將child加入到mFirstTouchTarget鏈表的表頭,並且將該表頭賦值給newTouchTarget(參見addTouchTarget方法),同時 alreadyDispatchedToNewTouchTarget置為true,說明有子view消費掉了該down事件。 if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) { // Child wants to receive touch within its bounds. mLastTouchDownTime = ev.getDownTime(); mLastTouchDownIndex = childIndex; mLastTouchDownX = ev.getX(); mLastTouchDownY = ev.getY(); newTouchTarget = addTouchTarget(child, idBitsToAssign); alreadyDispatchedToNewTouchTarget = true; break; } } } //如果newTouchTarget為null,並且 mFirstTouchTarget不為null,也即沒找到子View來消耗該事件,但是保存Touch事件的鏈表不為空,則把newTouchTarget賦值為最早加進(Least Recently added)mFirstTouchTarget鏈表的target。暫時沒完全搞明白這裡的具體意思,跟代碼都沒有走到這裡。 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; } } } //後面在處理MOVE和UP事件時,會直接根據上次的DOWN是否被消費掉來直接進行對應的處理。 if (mFirstTouchTarget == null) { // 如果沒有子view接受該事件,則直接把當前的ViewGroup當作普通的View看待,把事件傳遞給自己(詳見dispatchTransformedTouchEvent方法,注意第三個參數傳遞的是null)。 handled = dispatchTransformedTouchEvent(ev, canceled, null, TouchTarget.ALL_POINTER_IDS); } else { // 如果之前的DOWN事件被子view消費掉了,就會直接找到該子View對應的Target,將MOVE或UP事件傳遞給它們。 TouchTarget predecessor = null; TouchTarget target = mFirstTouchTarget; while (target != null) { final TouchTarget next = target.next; if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) { //如果該事件已經被消費掉了,則不再進行分發(該分支主要針對DOWN事件) handled = true; } else { //否則,就直接將DOWN或UP事件分發給目標Target(之前消費DOWN事件的view對應的target,注意dispatchTransformedTouchEvent的第三個參數為target.child),這裡要注意的是,如果intercepted為true,也就是MOVE或UP事件被攔截了,則cancelChild為true,則會分發一次CANCLE事件(注意dispatchTransformedTouchEvent的第二個參數)。 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; } } // 如果當前事件是CANCLE或UP,會調用resetTouchState方法,清空Touch狀態,這裡會清空mFirstTouchTarget鏈表,並將mFirstTouchTarget置為null 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; }

另外畫了張ViewGroup中dispatchTouchEvent方法代碼執行的流程圖,有助於大家把握整體邏輯:

關於上面提到的dispatchTransformedTouchEvent方法這裡就不多分析了,感興趣可以自行研究,另外ViewGroup中沒有複寫onTouchEvent方法。

下面重點看View中的dispatchTouchEvent方法。

 public boolean dispatchTouchEvent(MotionEvent event) { if (mInputEventConsistencyVerifier != null) { mInputEventConsistencyVerifier.onTouchEvent(event, 0); } if (onFilterTouchEventForSecurity(event)) { //noinspection SimplifiableIfStatement ListenerInfo li = mListenerInfo; if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED && li.mOnTouchListener.onTouch(this, event)) { return true; } if (onTouchEvent(event)) { return true; } } if (mInputEventConsistencyVerifier != null) { mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); } return false; }

很明顯,會先判斷該View有沒有綁定OnTouchListener監聽器,如果綁定並覆寫了onTouch,且onTouch返回true,那麼Touch事件就被消費掉,後面的onTouchEvent不會執行;如果沒被消費,才會執行onTouchEvent,根據其返回值判定事件是否被消費。這裡重點關注消費順序:onTouch先於onTouchEvent。

下面重點看View中的onTouchEvent方法。

 public boolean onTouchEvent(MotionEvent event) { final int viewFlags = mViewFlags; if ((viewFlags & ENABLED_MASK) == DISABLED) { if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) { setPressed(false); } // 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 & PFLAG_PREPRESSED) != 0; if ((mPrivateFlags & PFLAG_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. setPressed(true); } 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 |= PFLAG_PREPRESSED; if (mPendingCheckForTap == null) { mPendingCheckForTap = new CheckForTap(); } postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); } else { // Not inside a scrolling container, so show the feedback right away setPressed(true); checkForLongClick(0); } break; case MotionEvent.ACTION_CANCEL: setPressed(false); removeTapCallback(); removeLongPressCallback(); 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 & PFLAG_PRESSED) != 0) { // Remove any future long press/tap checks removeLongPressCallback(); setPressed(false); } } break; } return true; } return false; }

這裡重點關注:

1、onClick和onLongClick的執行時機:onClick在UP事件中執行,onLongClick在Down事件中執行,只是如果在Down事件中已經執行了onLongClick,那麼mHasPerformedLongPress變量會被置為true,這樣在UP事件中就會把onClick的回調remove掉,不再執行onClick。

2、只要該View是clickable的,就一定會消費掉Touch事件,只是如果該View是Disable的,雖然消費了事件,但不做任何處理。

另外大致說一下:源碼前面部分有個mTouchDelegate變量(預設null),如果不為null,會把Touch事件分發給它。具體意思是,假設有兩個視圖v1和touchDelegate1,它們布局互不重疊;如果設置了v1.setTouchDelegate(touchDelegate1),那麼v1的觸摸事件就會分發給touchDelegate1中的view。

為便於整體把握源碼流程,這裡同樣畫了個流程圖:

最後,關於整個Touch事件在View樹中的傳遞流程,同樣畫了張流程圖,看起來更直觀,有助於對整體流程的把控:

以上流程圖中有些地方文字錯位,應該不影響對流程的整體理解。

相對來說,事件的分發處理屬於Android中比較基礎的知識點,但想把整個流程完整串通,還是要花些時間的。這篇文章斷斷續續堅持寫下來還挺費勁的。

下篇文章,將透過一個Demo,結合8種不同情況,對Touch事件在View樹中傳遞時源碼的執行情況做一個詳細分析。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved