在分析Android事件分發機制前,明確android的兩大基礎控制項類型:View和ViewGroup。View即普通的控制項,沒有子佈局的,如Button、TextView. ViewGroup繼承自View,表示可以有子控制項,如Linearlayout、Listview這些。今天我們先來瞭解Vie ...
在分析Android事件分發機制前,明確android的兩大基礎控制項類型:View和ViewGroup。View即普通的控制項,沒有子佈局的,如Button、TextView. ViewGroup繼承自View,表示可以有子控制項,如Linearlayout、Listview這些。今天我們先來瞭解View的事件分發機制。
先看下代碼,非常簡單,只有一個Button,分別給它註冊了OnClick和OnTouch的點擊事件。1 btn.setOnClickListener(new View.OnClickListener() { 2 @Override 3 public void onClick(View v) { 4 Log.i("Tag", "This is button onClick event"); 5 } 6 }); 7 btn.setOnTouchListener(new View.OnTouchListener() { 8 @Override 9 public boolean onTouch(View v, MotionEvent event) { 10 Log.i("Tag", "This is button onTouch action" + event.getAction()); 11 return false; 12 } 13 });
運行一下項目,結果如下:
1 I/Tag: This is button onTouch action0 2 I/Tag: This is button onTouch action2 3 I/Tag: This is button onTouch action2 4 I/Tag: This is button onTouch action1 5 I/Tag: This is button onClick event
可以看到,onTouch是有先於onClick執行的,因此事件的傳遞順序是先onTouch,在到OnClick。具體為什麼這樣,下麵會通過源碼來說明。這時,我們可能註意到了,onTouch的方法是有返回值,這裡是返回false,我們將它改為true再運行一次,結果如下:
1 I/Tag: This is button onTouch action0 2 I/Tag: This is button onTouch action2 3 I/Tag: This is button onTouch action2 4 I/Tag: This is button onTouch action2 5 I/Tag: This is button onTouch action1對比兩次結果,我們發現onClick方法不再執行,為什麼會這樣,下麵我將通過源碼給大家一步步理清這個思路。 查看源碼時,首先要知道所有View類型控制項事件入口都是dispatchTouchEvent(),所以我們直接進入到View這個類裡面的dispatchTouchEvent()方法看一下。
1 public boolean dispatchTouchEvent(MotionEvent event) { 2 // If the event should be handled by accessibility focus first. 3 if (event.isTargetAccessibilityFocus()) { 4 // We don't have focus or no virtual descendant has it, do not handle the event. 5 if (!isAccessibilityFocusedViewOrHost()) { 6 return false; 7 } 8 // We have focus and got the event, then use normal event dispatch. 9 event.setTargetAccessibilityFocus(false); 10 } 11 boolean result = false; 12 if (mInputEventConsistencyVerifier != null) { 13 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 14 } 15 final int actionMasked = event.getActionMasked(); 16 if (actionMasked == MotionEvent.ACTION_DOWN) { 17 // Defensive cleanup for new gesture 18 stopNestedScroll(); 19 } 20 if (onFilterTouchEventForSecurity(event)) { 21 //noinspection SimplifiableIfStatement 22 ListenerInfo li = mListenerInfo; 23 if (li != null && li.mOnTouchListener != null 24 && (mViewFlags & ENABLED_MASK) == ENABLED 25 && li.mOnTouchListener.onTouch(this, event)) { 26 result = true; 27 } 28 if (!result && onTouchEvent(event)) { 29 result = true; 30 } 31 } 32 if (!result && mInputEventConsistencyVerifier != null) { 33 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 34 } 35 // Clean up after nested scrolls if this is the end of a gesture; 36 // also cancel it if we tried an ACTION_DOWN but we didn't want the rest 37 // of the gesture. 38 if (actionMasked == MotionEvent.ACTION_UP || 39 actionMasked == MotionEvent.ACTION_CANCEL || 40 (actionMasked == MotionEvent.ACTION_DOWN && !result)) { 41 stopNestedScroll(); 42 } 43 return result; 44 }從源碼第25行處可以看到,mOnTouchListener.onTouch()的方法首先被執行,如果li != null && li.mOnTouchListener != null&& (mViewFlags & ENABLED_MASK) == ENABLED&& li.mOnTouchListener.onTouch(this, event)都為真的話,result賦值為true,否則就執行onTouchEvent(event)方法。 從上面可以看到要符合條件有四個, 1、ListenerInfo li,它是view中的一個靜態類,裡面定義view的事件的監聽等等,所以有涉及到view的事件,ListenerInfo都會被實例化,因此li不為null 2、mOnTouchiListener是在setOnTouchListener方法裡面賦值的,只要touch事件被註冊,mOnTouchiListener一定不會null 3、 (mViewFlags & ENABLED_MASK) == ENABLED,是判斷當前點擊的控制項是否是enable的,button預設為enable,這個條件也恆定為true, 4、重點來了,li.mOnTouchListener.onTouch(this, event)就是回調控制項onTouch方法,當這個條件也為true時,result=true,onTouchEvent(event)將不會被執行。如果onTouch返回false,就會再執行onTouchEvent(event)方法。 我們接著再進入到onTouchEvent方法查看源碼。
1 public boolean onTouchEvent(MotionEvent event) { 2 final float x = event.getX(); 3 final float y = event.getY(); 4 final int viewFlags = mViewFlags; 5 final int action = event.getAction(); 6 if ((viewFlags & ENABLED_MASK) == DISABLED) { 7 if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) { 8 setPressed(false); 9 } 10 // A disabled view that is clickable still consumes the touch 11 // events, it just doesn't respond to them. 12 return (((viewFlags & CLICKABLE) == CLICKABLE 13 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 14 || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE); 15 } 16 if (mTouchDelegate != null) { 17 if (mTouchDelegate.onTouchEvent(event)) { 18 return true; 19 } 20 } 21 if (((viewFlags & CLICKABLE) == CLICKABLE || 22 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) || 23 (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) { 24 switch (action) { 25 case MotionEvent.ACTION_UP: 26 boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0; 27 if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) { 28 // take focus if we don't have it already and we should in 29 // touch mode. 30 boolean focusTaken = false; 31 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 32 focusTaken = requestFocus(); 33 } 34 if (prepressed) { 35 // The button is being released before we actually 36 // showed it as pressed. Make it show the pressed 37 // state now (before scheduling the click) to ensure 38 // the user sees it. 39 setPressed(true, x, y); 40 } 41 if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) { 42 // This is a tap, so remove the longpress check 43 removeLongPressCallback(); 44 // Only perform take click actions if we were in the pressed state 45 if (!focusTaken) { 46 // Use a Runnable and post this rather than calling 47 // performClick directly. This lets other visual state 48 // of the view update before click actions start. 49 if (mPerformClick == null) { 50 mPerformClick = new PerformClick(); 51 } 52 if (!post(mPerformClick)) { 53 performClick(); 54 } 55 } 56 } 57 if (mUnsetPressedState == null) { 58 mUnsetPressedState = new UnsetPressedState(); 59 } 60 if (prepressed) { 61 postDelayed(mUnsetPressedState, 62 ViewConfiguration.getPressedStateDuration()); 63 } else if (!post(mUnsetPressedState)) { 64 // If the post failed, unpress right now 65 mUnsetPressedState.run(); 66 } 67 removeTapCallback(); 68 } 69 mIgnoreNextUpEvent = false; 70 break; 71 case MotionEvent.ACTION_DOWN: 72 mHasPerformedLongPress = false; 73 if (performButtonActionOnTouchDown(event)) { 74 break; 75 } 76 // Walk up the hierarchy to determine if we're inside a scrolling container. 77 boolean isInScrollingContainer = isInScrollingContainer(); 78 // For views inside a scrolling container, delay the pressed feedback for 79 // a short period in case this is a scroll. 80 if (isInScrollingContainer) { 81 mPrivateFlags |= PFLAG_PREPRESSED; 82 if (mPendingCheckForTap == null) { 83 mPendingCheckForTap = new CheckForTap(); 84 } 85 mPendingCheckForTap.x = event.getX(); 86 mPendingCheckForTap.y = event.getY(); 87 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 88 } else { 89 // Not inside a scrolling container, so show the feedback right away 90 setPressed(true, x, y); 91 checkForLongClick(0); 92 } 93 break; 94 case MotionEvent.ACTION_CANCEL: 95 setPressed(false); 96 removeTapCallback(); 97 removeLongPressCallback(); 98 mInContextButtonPress = false; 99 mHasPerformedLongPress = false; 100 mIgnoreNextUpEvent = false; 101 break; 102 case MotionEvent.ACTION_MOVE: 103 drawableHotspotChanged(x, y); 104 // Be lenient about moving outside of buttons 105 if (!pointInView(x, y, mTouchSlop)) { 106 // Outside button 107 removeTapCallback(); 108 if ((mPrivateFlags & PFLAG_PRESSED) != 0) { 109 // Remove any future long press/tap checks 110 removeLongPressCallback(); 111 setPressed(false); 112 } 113 } 114 break; 115 } 116 return true; 117 } 118 return false; 119 }
從源碼的21行我們可以看出,該控制項可點擊就會進入到switch判斷中,當我們觸發了手指離開的實際,則會進入到MotionEvent.ACTION_UP這個case當中。我們接著往下看,在源碼的50行,調用到了mPerformClick()方法,我們繼續進入到這個方法的源碼看看。
1 public boolean performClick() { 2 final boolean result; 3 final ListenerInfo li = mListenerInfo; 4 if (li != null && li.mOnClickListener != null) { 5 playSoundEffect(SoundEffectConstants.CLICK); 6 li.mOnClickListener.onClick(this); 7 result = true; 8 } else { 9 result = false; 10 } 11 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 12 return result; 13 }
現在我們可以看到,只要ListenerInfo和mOnClickListener不為null就會調用onClick這個方法,之前說過,只要有監聽事件,ListenerInfo就不為null,帶mOnClickListener又是在哪裡賦值呢?我們再繼續看下它的源碼。
1 public void setOnClickListener(@Nullable OnClickListener l) { 2 if (!isClickable()) { 3 setClickable(true); 4 } 5 getListenerInfo().mOnClickListener = l; 6 }
看到這裡一切就清楚了,當我們調用setOnClickListener方法來給按鈕註冊一個點擊事件時,就會給mOnClickListener賦值。整個分發事件的順序是onTouch()-->onTouchEvent(event)-->performClick()-->OnClick()。
現在我們可以解決之前的問題。
1、onTouch方法是優先於OnClick,所以是執行了onTouch,再執行onClick。
2、無論是dispatchTouchEvent還是onTouchEvent,如果返回true表示這個事件已經被消費、處理了,不再往下傳了。在dispathTouchEvent的源碼里可以看到,如果onTouchEvent返回了true,那麼它也返回true。如果dispatchTouchEvent在執行onTouch監聽的時候,onTouch返回了true,那麼它也返回true,這個事件提前被onTouch消費掉了。就不再執行onTouchEvent了,更別說onClick監聽了。