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);}

上面PhoneWindow的superDispatchTouchEvent直接返回了DecorView的superDispatchTouchEvent,而DecorView又是FrameLayout的子类,FrameLayout又是ViewGroup的子类,touch事件就被分发到的我们们定义的xmlLayout布局中。接下来分析ViewGroup的事件分发。

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相关推荐

  1. Android系统源码分析--Activity的finish过程

    上一篇我们分析了Activity的启动流程,由于代码量很大,还是没有分析的很详细,但是基本流程都出来了,更详细的东西还是要去看源码.这一章来分析Activity的finish过程,分析一下finish ...

  2. 【Android 事件分发】事件分发源码分析 ( Activity 中各层级的事件传递 | Activity -> PhoneWindow -> DecorView -> ViewGroup )

    Android 事件分发 系列文章目录 [Android 事件分发]事件分发源码分析 ( 驱动层通过中断传递事件 | WindowManagerService 向 View 层传递事件 ) [Andr ...

  3. 【Android 事件分发】MotionEvent.ACTION_DOWN 按下事件分发流程( Activity | ViewGroup | View )

    Android 事件分发 系列文章目录 [Android 事件分发]事件分发源码分析 ( 驱动层通过中断传递事件 | WindowManagerService 向 View 层传递事件 ) [Andr ...

  4. 【Android 启动过程】Activity 启动源码分析 ( Activity -> AMS、主线程阶段 )

    文章目录 一.Activity 启动源码分析 ( Activity -> AMS 阶段 ) 一.Activity 启动源码分析 ( Activity -> AMS 阶段 ) 调用 star ...

  5. Android HandlerThread 源码分析

    HandlerThread 简介: 我们知道Thread线程是一次性消费品,当Thread线程执行完一个耗时的任务之后,线程就会被自动销毁了.如果此时我们又有一 个耗时任务需要执行,我们不得不重新创建 ...

  6. Android ADB 源码分析(三)

    前言 之前分析的两篇文章 Android Adb 源码分析(一) 嵌入式Linux:Android root破解原理(二) 写完之后,都没有写到相关的实现代码,这篇文章写下ADB的通信流程的一些细节 ...

  7. 【Android SDM660源码分析】- 02 - UEFI XBL QcomChargerApp充电流程代码分析

    [Android SDM660源码分析]- 02 - UEFI XBL QcomChargerApp充电流程代码分析 一.加载 UEFI 默认应用程序 1.1 LaunchDefaultBDSApps ...

  8. 【Android SDM660源码分析】- 03 - UEFI XBL GraphicsOutput BMP图片显示流程

    [Android SDM660源码分析]- 03 - UEFI XBL GraphicsOutput BMP图片显示流程 1. GraphicsOutput.h 2. 显示驱动初化 DisplayDx ...

  9. 【Android SDM660源码分析】- 01 - 如何创建 UEFI XBL Protocol DXE_DRIVER 驱动及UEFI_APPLICATION 应用程序

    [Android SDM660源码分析]- 01 - 如何创建 UEFI XBL Protocol DXE_DRIVER 驱动及UEFI_APPLICATION 应用程序 一.创建DXE_DRIVER ...

最新文章

  1. 给网站添加icon图标
  2. node.js php模板,node.js中EJS 模板的使用教程
  3. JQuery 获取自身的HTml代码
  4. Swift 新特性 - 访问控制(Access Control)
  5. secureCRT回滚行数
  6. 在Python Shell中输入print 'hello'总是报语法错误
  7. springMVC框架下JQuery传递并解析Json数据
  8. python dicom 测量_python对DICOM图像的读取方法详解
  9. asp.net中FCKeditor的调用(31)
  10. 阶段3 2.Spring_07.银行转账案例_9 基于子类的动态代理
  11. 负载均衡技术沙龙2期圆满结束(现场图文、PPT)
  12. install在python里什么意思_“pip install”和“python-m pip install”有什么区别?
  13. 81192 祖国期盼着你返航
  14. 数据管理平台(DMP)简介
  15. python闲鱼二手爬虫_Python 爬虫咸鱼版
  16. 【windows】window10打开图片显示黑屏,一直打不开
  17. 框架学习:框架是什么以及框架怎么学
  18. 安卓10不支持qmc解码_鸿图之下iOS和安卓互通吗-10月21日不删档测试服务器规则介绍...
  19. 死宅BALBALBA的奇妙冒险(0)——C语萌新的新手村
  20. 雨果奖得主刘慈欣(《三体》作者)如何看待人工智能?

热门文章

  1. linux mktime函数会受当前环境变量设置的时区影响
  2. V4L2 driver(一). 整体框架
  3. AB1601低功耗注意事项
  4. 机器学习中样本不平衡处理办法
  5. CMM与CMMI的关系
  6. 建立新冠病毒群体免疫屏障——数学建模
  7. ARM Trustzone的安全扩展介绍-精简版-思维导图
  8. Dockerfile项目环境介绍
  9. java环境教程_window下Java环境配置图文教程
  10. inline hook __usercall 函数