Android触摸事件源码分析:Activity-ViewGroup-View
Activity中
當屏幕有touch事件時,首先調用Activity的dispatchTouchEvent方法
/*** Called to process touch screen events. You can override this to* intercept all touch screen events before they are dispatched to the* window. Be sure to call this implementation for touch screen events* that should be handled normally.** @param ev The touch screen event.** @return boolean Return true if this event was consumed.*/public boolean dispatchTouchEvent(MotionEvent ev) {if (ev.getAction() == MotionEvent.ACTION_DOWN) {onUserInteraction();}if (getWindow().superDispatchTouchEvent(ev)) {return true;}return onTouchEvent(ev); } 只有ACTION_DOWN事件派發時調運了onUserInteraction方法,直接跳進去可以看見是一個空方法。接著往下看
首先分析Activity的attach方法可以發現getWindow()返回的就是PhoneWindow對象(PhoneWindow為抽象Window的實現子類),那就簡單了,也就相當于PhoneWindow類的方法,而PhoneWindow類實現于Window抽象類,所以先看下Window類中抽象方法的定義,如下:
<span style="font-size:24px;">/*** Used by custom windows, such as Dialog, to pass the touch screen event* further down the view hierarchy. Application developers should* not need to implement or call this.*用戶不需要重寫實現的方法,實質也不能,在Activity中沒有提供重寫的機會,因為Window是以組</span><pre name="code" class="java"><span style="font-size:24px;">*</span><span style="font-family: Arial, Helvetica, sans-serif;"><span style="font-size:18px;">合模式與Activity建立關系的</span></span> */ public abstract boolean superDispatchTouchEvent(MotionEvent event); PhoneWindow里看下Window抽象方法的實現:@Overridepublic boolean superDispatchTouchEvent(MotionEvent event) {return mDecor.superDispatchTouchEvent(event);} 這里出現了mDecor變量,是啥?其實是DecorView的實例,有人會問DecorView又是啥?
在PhoneWindow類里發現,mDecor是DecorView類的實例,同時DecorView是PhoneWindow的內部類。最驚人的發現是DecorView extends FrameLayout implements RootViewSurfaceTaker,看見沒有?它是一個真正Activity的root view,它繼承了FrameLayout。
不知道大家是不是熟悉Android App開發技巧中關于UI布局優化使用的SDK工具Hierarchy Viewer,打開的時候在最上面會有個DecorView$PhoneWindow的框框
Activity中setContentView時,把我們編寫的xmlLayout文件放置在一個id為content的FrameLayout的布局(DecorView)中,這也就是為啥Activity的setContentView方法叫set content view了,就是把我們的xml放入了這個id為content的FrameLayout中
講完了DecorView,我們在來看看mDecor.superDispatchTouchEvent(event):
public boolean superDispatchTouchEvent(MotionEvent event) {return super.dispatchTouchEvent(event);}
Activity的dispatchTouchEvent方法的if (getWindow().superDispatchTouchEvent(ev))本質執行的是一個ViewGroup的dispatchTouchEvent方法(這個ViewGroup是Activity特有的root view,也就是id為content的FrameLayout布局)
在Activity的觸摸屏事件派發中:Activity,PhoneWindow,DecorView,ViewGroup
1,首先會觸發Activity的dispatchTouchEvent方法。
2,dispatchTouchEvent方法中如果是ACTION_DOWN的情況下會接著觸發onUserInteraction方法。
3,接著在dispatchTouchEvent方法中會通過Activity的root View(id為content的FrameLayout),實質是ViewGroup,通過super.dispatchTouchEvent把touchevent派發給各個activity的子view,也就是我們再Activity.onCreat方法中setContentView時設置的view。
4,若Activity下面的子view攔截了touchevent事件(返回true)則Activity.onTouchEvent方法就不會執行。
ViewGroup中
既然Activity中的DecorView是ViewGroup的子類調用了dispatchTouchEvent方法,來看看這個方法:
@Overridepublic boolean dispatchTouchEvent(MotionEvent ev) {if (mInputEventConsistencyVerifier != null) {mInputEventConsistencyVerifier.onTouchEvent(ev, 1);}// If the event targets the accessibility focused view and this is it, start// normal event dispatch. Maybe a descendant is what will handle the click.if (ev.isTargetAccessibilityFocus() && isAccessibilityFocusedViewOrHost()) {ev.setTargetAccessibilityFocus(false);}boolean handled = false;if (onFilterTouchEventForSecurity(ev)) {final int action = ev.getAction();final int actionMasked = action & MotionEvent.ACTION_MASK; /*清除以往的Touch狀態然后開始新的手勢。在這里你會發現cancelAndClearTouchTargets(ev)方法中有一個非常重要的操作就是將mFirstTouchTarget設置為了null(剛開始分析大眼瞄一眼沒留意,結果越往下看越迷糊,所以這個是分析ViewGroup的dispatchTouchEvent方法第一步中重點要記住的一個地方),接著在resetTouchState()方法中重置Touch狀態標識。*/// 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) {// 說明當事件為ACTION_DOWN或者mFirstTouchTarget不為null(即已經找到能夠接收touch事件的目標組件)時if成立,否則if不成立,然后將intercepted設置為true,也即攔截事件 final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;if (!disallowIntercept) { // 如果沒有禁止攔截,就調用onInterceptTouchEvent方法,touch事件就繼續傳遞給子View,默認不攔截intercepted = onInterceptTouchEvent(ev);ev.setAction(action); // restore action in case it was changed存儲動作以防止它改變} else {intercepted = false; // 如果禁止攔截,intercepted就是false,touch事件就繼續傳遞給子View}} else {// There are no touch targets and this action is not an initial down// so this view group continues to intercept touches.如果沒有touch目標組件和down事件,這個viewgroup就是繼續攔截touchintercepted = true;}// If intercepted, start normal event dispatch. Also if there is already// a view that is handling the gesture, do normal event dispatch.if (intercepted || mFirstTouchTarget != null) {ev.setTargetAccessibilityFocus(false);}// Check for cancelation.檢查取消,然后將結果賦值給局部boolean變量canceledfinal boolean canceled = resetCancelNextUpFlag(this)|| actionMasked == MotionEvent.ACTION_CANCEL;// Update list of touch targets for pointer down, if needed. 默認是true,作用是是否把事件分發給多個子Viewfinal boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;TouchTarget newTouchTarget = null;boolean alreadyDispatchedToNewTouchTarget = false;if (!canceled && !intercepted) { // 如果沒有被取消也沒有被攔截,就開始進行分發事件了// If the event is targeting accessiiblity focus we give it to the// view that has accessibility focus and if it does not handle it// we clear the flag and dispatch the event to all children as usual.// We are looking up the accessibility focused host to avoid keeping// state since these events are very rare.View childWithAccessibilityFocus = ev.isTargetAccessibilityFocus()? findChildWithAccessibilityFocus() : null;if (actionMasked == MotionEvent.ACTION_DOWN|| (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)|| actionMasked == MotionEvent.ACTION_HOVER_MOVE) {final int actionIndex = ev.getActionIndex(); // always 0 for downfinal 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 (newTouchTarget == null && childrenCount != 0) { // childrenCount個數是否不為0且新的touch target是空,目的就是為了找到touch targetfinal float x = ev.getX(actionIndex);final float y = ev.getY(actionIndex);// Find a child that can receive the event.// Scan children from front to back.final ArrayList<View> preorderedList = buildOrderedChildList();//子View的list集合preorderedListfinal boolean customOrder = preorderedList == null&& isChildrenDrawingOrderEnabled();final View[] children = mChildren;for (int i = childrenCount - 1; i >= 0; i--) {//for循環i從childrenCount - 1開始遍歷到0,倒序遍歷所有的子viewfinal int childIndex = customOrder? getChildDrawingOrder(childrenCount, i) : i;final View child = (preorderedList == null)? children[childIndex] : preorderedList.get(childIndex);// If there is a view that has accessibility focus we want it// to get the event first and if not handled we will perform a// normal dispatch. We may do a double iteration but this is// safer given the timeframe.if (childWithAccessibilityFocus != null) {if (childWithAccessibilityFocus != child) {continue;}childWithAccessibilityFocus = null;i = childrenCount - 1;}if (!canViewReceivePointerEvents(child)|| !isTransformedTouchPointInView(x, y, child, null)) {ev.setTargetAccessibilityFocus(false);continue;}newTouchTarget = getTouchTarget(child); //這一句很重要,通過getTouchTarget去查找當前子View是否在mFirstTouchTarget.next這條target鏈中的某一個target中,如果在則返回這個target,否則返回nullif (newTouchTarget != null) {//找到了接收Touch事件的子View,即newTouchTarget,那么,既然已經找到了,所以執行break跳出for循環// 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);/***調用方法dispatchTransformedTouchEvent()將Touch事件傳遞給特定的子View。該方法十分重要,在該方法中為一個遞歸調用,會遞歸調用 dispatchTouchEvent()方法。在dispatchTouchEvent()中如果子View為ViewGroup并且Touch沒有被攔截那么遞歸調用dispatchTouchEvent(),如果子View為View那么就會調用其onTouchEvent()。dispatchTransformedTouchEvent方法如果返回true則表示子View消費掉該事件,同時進入該if判斷。滿足if語句后重要的操作有:1,給newTouchTarget賦值; 2,給alreadyDispatchedToNewTouchTarget賦值為true; 3,執行break,因為該for循環遍歷子View判斷哪個子View接受Touch事件,既然已經找到了就跳出該外層for循環;*/if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {// Child wants to receive touch within its bounds.mLastTouchDownTime = ev.getDownTime();if (preorderedList != null) {// childIndex points into presorted list, find original indexfor (int j = 0; j < childrenCount; j++) {if (children[childIndex] == mChildren[j]) {mLastTouchDownIndex = j;break;}}} else {mLastTouchDownIndex = childIndex;}mLastTouchDownX = ev.getX();mLastTouchDownY = ev.getY();newTouchTarget = addTouchTarget(child, idBitsToAssign);alreadyDispatchedToNewTouchTarget = true;break;}// The accessibility focus didn't handle the event, so clear// the flag and do a normal dispatch to all children.ev.setTargetAccessibilityFocus(false);}if (preorderedList != null) preorderedList.clear();}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;}}}/***因為在dispatchTransformedTouchEvent()會調用遞歸調用dispatchTouchEvent()和onTouchEvent(),所以dispatchTransformedTouchEvent()的返回值實際上是由 onTouchEvent()決定的。簡單地說onTouchEvent()是否消費了Touch事件的返回值決定了dispatchTransformedTouchEvent()的返回值,從而決定mFirstTouchTarget是否為null,進一步決定了ViewGroup 是否處理Touch事件 */// 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;}
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:*使用這個函數要小心,它和View的onTouchEvent有十分復雜的交互,事件能夠按照下列的順序被收到:* <ol>* <li> You will receive the down event here.1,你將先收到down事件* <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.* 2,down事件要么被子View的handle,要么被這個viewgroup的onTouchEvent方法處理* <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(). * 3,只要onInterceptTouchEvent返回false,后面的每個事件都會繼續分發到touch target執行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.* 4,onInterceptTouchEvent返回true, 交給這個ViewGroup的onTouchEvent處理。* </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;} 看到了吧,這個方法算是ViewGroup不同于View特有的一個事件派發調運方法。在源碼中可以看到這個方法實現很簡單,但是有一堆注釋。其實上面分析了,如果ViewGroup的onInterceptTouchEvent返回false就不阻止事件繼續傳遞派發,否則阻止傳遞派發。
如上就是所有ViewGroup關于觸摸屏事件的傳遞機制源碼分析。具體總結如下:
1,Android事件派發是先傳遞到最頂級的ViewGroup,再由ViewGroup遞歸傳遞到View的。
2,在ViewGroup中可以通過onInterceptTouchEvent方法對事件傳遞進行攔截,3,onInterceptTouchEvent方法
? ?1)返回true ? 代表不允許事件繼續向子View傳遞,則交給這個ViewGroup的onTouchEvent處理
? ?2)返回false 代表不對事件進行攔截,默認返回false,則交給子View的dispatchTouchEvent方法處理
4,事件傳遞到子view 的 dispatchTouchEvent方法中,通過方法傳遞到當前View的onTouchEvent方法中:
(1)如果返回true,那么這個事件就會止于該view。
(2)如果返回 false ,那么這個事件會從這個子view 往上傳遞,而且都是傳遞到父View的onTouchEvent 來接收。
(3)如果傳遞到ViewGroup的 onTouchEvent 也返回 false 的話,則繼續傳遞到Activity的onTouchEvent中,如果還是false,則這個事件就會“消失“;事件向上傳遞到中間的任何onTouchEvent方法中,如果返回true,則事件被消費掉,不會再傳遞。
View中觸摸消息機制:
在Android中你只要觸摸控件首先都會觸發控件的dispatchTouchEvent方法(其實這個方法一般都沒在具體的控件類中,而在他的父類View中),所以我們先來看下View的dispatchTouchEvent方法
View中的觸摸消息機制:/*** Pass the touch screen motion event down to the target view, or this* view if it is the target.** @param event The motion event to be dispatched.* @return True if the event was handled by the view, false otherwise.*/public boolean dispatchTouchEvent(MotionEvent event) {// If the event should be handled by accessibility focus first.if (event.isTargetAccessibilityFocus()) {// We don't have focus or no virtual descendant has it, do not handle the event.if (!isAccessibilityFocusedViewOrHost()) {return false;}// We have focus and got the event, then use normal event dispatch.event.setTargetAccessibilityFocus(false);}boolean result = false;if (mInputEventConsistencyVerifier != null) {mInputEventConsistencyVerifier.onTouchEvent(event, 0);}final int actionMasked = event.getActionMasked();if (actionMasked == MotionEvent.ACTION_DOWN) {// Defensive cleanup for new gesturestopNestedScroll();}if (onFilterTouchEventForSecurity(event)) { // 判斷當前View是否沒被遮住//noinspection SimplifiableIfStatement ListenerInfo局部變量,ListenerInfo是View的靜態內部類,用來定義一堆關于View的XXXListener等方法ListenerInfo li = mListenerInfo;/**一,首先判斷是不是設置onTouch監聽器,onTouch的返回值 * 首先li對象自然不會為null, li.mOnTouchListener是不是null取決于控件(View)是否設置setOnTouchListener監聽 * 接著通過位與運算確定控件(View)是不是ENABLED 的,默認控件都是ENABLED 的* 接著判斷onTouch的返回值是不是true*/if (li != null && li.mOnTouchListener != null&& (mViewFlags & ENABLED_MASK) == ENABLED&& li.mOnTouchListener.onTouch(this, event)) {result = true; //如果設置了onTouchListener,并且onTouch返回時true,result就是true,下一句if就不執行了,onTouchEvent和onClick就不執行了}//上面的執行了result等于true,這句就不執行了。如果result是false,就執行onTouchEvent,onTouchEvent中有執行onClick的步驟if (!result && onTouchEvent(event)) {result = true;}}if (!result && mInputEventConsistencyVerifier != null) {mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);}// Clean up after nested scrolls if this is the end of a gesture;// also cancel it if we tried an ACTION_DOWN but we didn't want the rest// of the gesture.if (actionMasked == MotionEvent.ACTION_UP ||actionMasked == MotionEvent.ACTION_CANCEL ||(actionMasked == MotionEvent.ACTION_DOWN && !result)) {stopNestedScroll();}return result;} 如果 if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED && li.mOnTouchListener.onTouch(this, event))語句有一個為false則 if (!result && onTouchEvent(event))就會執行,如果onTouchEvent(event)返回false則dispatchTouchEvent返回false,否則返回true。
控件觸摸就會調運dispatchTouchEvent方法, 而在dispatchTouchEvent中先執行的是onTouch方法,所以驗證了實例結論總結中的onTouch優先于onClick執行道理。如果控件是ENABLE且在onTouch方法里返回了true則dispatchTouchEvent方法也返回true,不會再繼續往下執行;
? ? ?反之,onTouch返回false則會繼續向下執行onTouchEvent方法,且dispatchTouchEvent的返回值與onTouchEvent返回值相同。
所以依據這個結論和上面實例打印結果你指定已經大膽猜測認為onClick一定與onTouchEvent有關系?
總結結論
在View的觸摸屏傳遞機制中通過分析dispatchTouchEvent方法源碼我們會得出如下基本結論:
1,觸摸控件(View)首先執行dispatchTouchEvent方法。
2,在dispatchTouchEvent方法中先執行onTouch方法,后執行onClick方法(onClick方法在onTouchEvent中執行,下面會分析)。
3,如果控件(View)的onTouch返回false或者mOnTouchListener為null(控件沒有設置setOnTouchListener方法)或者控件不是enable的情況下會調運onTouchEvent,dispatchTouchEvent返回值與onTouchEvent返回一樣。
4,如果控件不是enable的設置了onTouch方法也不會執行,只能通過重寫控件的onTouchEvent方法處理(上面已經處理分析了),dispatchTouchEvent返回值與onTouchEvent返回一樣。
5,如果控件(View)是enable且onTouch返回true情況下,dispatchTouchEvent直接返回true,不會調用onTouchEvent方法。
View的dispatchTouchEvent方法中調運的onTouchEvent方法
/*** Implement this method to handle touch screen motion events.* <p>* If this method is used to detect click actions, it is recommended that* the actions be performed by implementing and calling* {@link #performClick()}. This will ensure consistent system behavior,* including:* <ul>* <li>obeying click sound preferences* <li>dispatching OnClickListener calls* <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when* accessibility features are enabled* </ul>** @param event The motion event.* @return True if the event was handled, false otherwise.*/public boolean onTouchEvent(MotionEvent event) {final float x = event.getX();final float y = event.getY();final int viewFlags = mViewFlags;if ((viewFlags & ENABLED_MASK) == DISABLED) { // 組件設置的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)) { //如果組件是enabled且可點擊,或者可長點擊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. // 首先判斷了是否按下過,同時是不是可以得到焦點,然后嘗試獲取焦點,然后判斷如果不是longPressed則通過post在UI Thread中執行一個PerformClick的Runnable,也就是performClick方法。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, x, y);}if (!mHasPerformedLongPress) {// This is a tap, so remove the longpress checkremoveLongPressCallback();// Only perform take click actions if we were in the pressed stateif (!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. // 使用post一個Runnable的PerformClick的任務類而不是直接調用performClick的方法。if (mPerformClick == null) {mPerformClick = new PerformClick();}if (!post(mPerformClick)) {performClick();// 終于找到了,onClick方法在performClick的函數中}}}if (mUnsetPressedState == null) {mUnsetPressedState = new UnsetPressedState();}if (prepressed) {postDelayed(mUnsetPressedState,ViewConfiguration.getPressedStateDuration());} else if (!post(mUnsetPressedState)) {// If the post failed, unpress right nowmUnsetPressedState.run();}removeTapCallback();}break;// ACTION_DOWN與ACTION_MOVE都進行了一些必要的設置與置位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();}mPendingCheckForTap.x = event.getX();mPendingCheckForTap.y = event.getY();postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());} else {// Not inside a scrolling container, so show the feedback right awaysetPressed(true, x, y);checkForLongClick(0);}break;case MotionEvent.ACTION_CANCEL:setPressed(false);removeTapCallback();removeLongPressCallback();break;case MotionEvent.ACTION_MOVE:drawableHotspotChanged(x, y);// Be lenient about moving outside of buttonsif (!pointInView(x, y, mTouchSlop)) {// Outside buttonremoveTapCallback();if ((mPrivateFlags & PFLAG_PRESSED) != 0) {// Remove any future long press/tap checksremoveLongPressCallback();setPressed(false);}}break;}return true;}return false;} <span style="font-size:24px;">/*** Call this view's OnClickListener, if it is defined. Performs all normal* actions associated with clicking: reporting accessibility event, playing* a sound, etc.*調用這個view的OnClickListener方法。* @return True there was an assigned OnClickListener that was called, false* otherwise is returned.*/public boolean performClick() {final boolean result;final ListenerInfo li = mListenerInfo;if (li != null && li.mOnClickListener != null) { // 和dispatchTouchEvent中的判斷一樣,li自然不是null,如果設置了OnclickListener那么 li.mOnClickListener也不為空playSoundEffect(SoundEffectConstants.CLICK);li.mOnClickListener.onClick(this); // 這個是重點!!!!!,執行這個View的Onclick方法,返回trueresult = true;} else {result = false;}sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);return result;} </span>
猜的沒錯onClick就在onTouchEvent中執行的,而且是在onTouchEvent的ACTION_UP事件中執行的
總結結論
1,onTouchEvent方法中會在ACTION_UP分支中觸發onClick的監聽。
2,當dispatchTouchEvent在進行事件分發的時候,只有前一個action返回true,才會觸發下一個action。
參考:http://blog.csdn.net/yanbober/article/details/45887547
總結
以上是生活随笔為你收集整理的Android触摸事件源码分析:Activity-ViewGroup-View的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Eclipse调试Android开发工具
- 下一篇: Android PullToRefres