一、View的dispatchTouchEvent和onTouchEvent

探讨Android事件传递机制前,明确android的两大基础控件类型:View和ViewGroup。View即普通的控件,没有子布局的,如Button、TextView. ViewGroup继承自View,表示可以有子控件,如Linearlayout、Listview这些。而事件即MotionEvent,最重要的有3个:
(1)MotionEvent.ACTION_DOWN  按下View,是所有事件的开始
(2)MotionEvent.ACTION_MOVE   滑动事件
(3)MotionEvent.ACTION_UP       与down对应,表示抬起
另外,明确事件传递机制的最终目的都是为了触发执行View的点击监听和触摸监听:
******.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i(tag, "testLinelayout---onClick...");
}
});

*******.setOnTouchListener(new View.OnTouchListener() {

@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub

return false;
}
});

我们简称为onClick监听和onTouch监听,一般程序会注册这两个监听。从上面可以看到,onTouch监听里默认return false。不要小看了这个return false,后面可以看到它有大用。
对于View来说,事件传递机制有两个函数:dispatchTouchEvent负责分发事件,在dispatch***里又会调用onTouchEvent表示执行事件,或者说消费事件,结合源码分析其流程。事件传递的入口是View的dispatchTouchEvent()函数:
[java] view plaincopy print?
  1. <span style="font-size:18px;">    /**
  2. * Pass the touch screen motion event down to the target view, or this
  3. * view if it is the target.
  4. *
  5. * @param event The motion event to be dispatched.
  6. * @return True if the event was handled by the view, false otherwise.
  7. */
  8. public boolean dispatchTouchEvent(MotionEvent event) {
  9. if (mInputEventConsistencyVerifier != null) {
  10. mInputEventConsistencyVerifier.onTouchEvent(event, 0);
  11. }
  12. if (onFilterTouchEventForSecurity(event)) {
  13. //noinspection SimplifiableIfStatement
  14. ListenerInfo li = mListenerInfo;
  15. if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
  16. && li.mOnTouchListener.onTouch(this, event)) {
  17. return true;
  18. }
  19. if (onTouchEvent(event)) {
  20. return true;
  21. }
  22. }
  23. if (mInputEventConsistencyVerifier != null) {
  24. mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
  25. }
  26. return false;
  27. }</span>

找到这个判断:

            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
                    && li.mOnTouchListener.onTouch(this, event)) {
                return true;
            }
他会执行View的OnTouchListener.onTouch这个函数,也就是上面说的onTouch监听。里面有三个判断,如果三个都为1,就会执行return true,不往下走了。而默认的onTouch监听返回false,只要一个是false,就不会返回true。接着往下看,程序执行onTouchEvent:
[java] view plaincopy print?
  1. <span style="font-size:18px;">            if (onTouchEvent(event)) {
  2. return true;
  3. }</span>

onTouchEvent的源码比较多,贴最重要的:

[java] view plaincopy print?
  1. <span style="font-size:18px;">                        if (!mHasPerformedLongPress) {
  2. // This is a tap, so remove the longpress check
  3. removeLongPressCallback();
  4. // Only perform take click actions if we were in the pressed state
  5. if (!focusTaken) {
  6. // Use a Runnable and post this rather than calling
  7. // performClick directly. This lets other visual state
  8. // of the view update before click actions start.
  9. if (mPerformClick == null) {
  10. mPerformClick = new PerformClick();
  11. }
  12. if (!post(mPerformClick)) {
  13. <span style="color:#ff0000;"> performClick();</span>
  14. }
  15. }
  16. }</span>

可以看到有个performClick(),它的源码里有这么一句 li.mOnClickListener.onClick(this);

[java] view plaincopy print?
  1. <span style="font-size:18px;">    public boolean performClick() {
  2. sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
  3. ListenerInfo li = mListenerInfo;
  4. if (li != null && li.mOnClickListener != null) {
  5. playSoundEffect(SoundEffectConstants.CLICK);
  6. <span style="color:#ff0000;"><strong>li.mOnClickListener.onClick(this);</strong></span>
  7. return true;
  8. }
  9. return false;
  10. }</span>

终于对上了,它执行了我们注册的onClick监听。当然执行前会经过一系列判断,是否注册了监听等。
总结:

1、事件入口是dispatchTouchEvent(),它会先执行注册的onTouch监听,如果一切顺利的话,接着执行onTouchEvent,在onTouchEvent里会执行onClick监听。
2、无论是dispatchTouchEvent还是onTouchEvent,如果返回true表示这个事件已经被消费、处理了,不再往下传了。在dispathTouchEvent的源码里可以看到,如果onTouchEvent返回了true,那么它也返回true。如果dispatch***在执行onTouch监听的时候,onTouch返回了true,那么它也返回true,这个事件提前被onTouch消费掉了。就不再执行onTouchEvent了,更别说onClick监听了。
3、我们通常在onTouch监听了设置图片一旦被触摸就改变它的背景、透明度之类的,这个onTouch表示事件的时机。而在onClick监听了去具体干某些事。
下面通过代码来说明,自定义一个TestButton继承自Button,重写它的dispath***和onTouchEvent方法,为了简单只关注down和up事件。
[java] view plaincopy print?
  1. <span style="font-size:18px;">package org.yanzi.ui;
  2. import android.content.Context;
  3. import android.util.AttributeSet;
  4. import android.util.Log;
  5. import android.view.MotionEvent;
  6. import android.widget.Button;
  7. public class TestButton extends Button {
  8. private final static String tag = "yan";
  9. public TestButton(Context context, AttributeSet attrs) {
  10. super(context, attrs);
  11. // TODO Auto-generated constructor stub
  12. }
  13. @Override
  14. public boolean onTouchEvent(MotionEvent event) {
  15. // TODO Auto-generated method stub
  16. switch(event.getAction()){
  17. case MotionEvent.ACTION_DOWN:
  18. Log.i(tag, "TestButton-onTouchEvent-ACTION_DOWN...");
  19. break;
  20. case MotionEvent.ACTION_UP:
  21. Log.i(tag, "TestButton-onTouchEvent-ACTION_UP...");
  22. break;
  23. default:break;
  24. }
  25. return super.onTouchEvent(event);
  26. }
  27. @Override
  28. public boolean dispatchTouchEvent(MotionEvent event) {
  29. // TODO Auto-generated method stub
  30. switch(event.getAction()){
  31. case MotionEvent.ACTION_DOWN:
  32. Log.i(tag, "TestButton-dispatchTouchEvent-ACTION_DOWN...");
  33. break;
  34. case MotionEvent.ACTION_UP:
  35. Log.i(tag, "TestButton-dispatchTouchEvent-ACTION_UP...");
  36. break;
  37. default:break;
  38. }
  39. return super.dispatchTouchEvent(event);
  40. }
  41. }
  42. </span>

在Activity里注册两个监听:

[java] view plaincopy print?
  1. <span style="font-size:18px;">      testBtn.setOnClickListener(new View.OnClickListener() {
  2. @Override
  3. public void onClick(View v) {
  4. // TODO Auto-generated method stub
  5. Log.i(tag, "testBtn---onClick...");
  6. }
  7. });
  8. testBtn.setOnTouchListener(new View.OnTouchListener() {
  9. @Override
  10. public boolean onTouch(View v, MotionEvent event) {
  11. // TODO Auto-generated method stub
  12. switch(event.getAction()){
  13. case MotionEvent.ACTION_DOWN:
  14. Log.i(tag, "testBtn-onTouch-ACTION_DOWN...");
  15. break;
  16. case MotionEvent.ACTION_UP:
  17. Log.i(tag, "testBtn-onTouch-ACTION_UP...");
  18. break;
  19. default:break;
  20. }
  21. return false;
  22. }
  23. });</span>

同时复写Activity的dispatch方法和onTouchEvent方法:

[java] view plaincopy print?
  1. <span style="font-size:18px;">@Override
  2. public boolean dispatchTouchEvent(MotionEvent ev) {
  3. // TODO Auto-generated method stub
  4. switch(ev.getAction()){
  5. case MotionEvent.ACTION_DOWN:
  6. Log.i(tag, "MainActivity-dispatchTouchEvent-ACTION_DOWN...");
  7. break;
  8. case MotionEvent.ACTION_UP:
  9. Log.i(tag, "MainActivity-dispatchTouchEvent-ACTION_UP...");
  10. break;
  11. default:break;
  12. }
  13. return super.dispatchTouchEvent(ev);
  14. }
  15. @Override
  16. public boolean onTouchEvent(MotionEvent event) {
  17. // TODO Auto-generated method stub
  18. switch(event.getAction()){
  19. case MotionEvent.ACTION_DOWN:
  20. Log.i(tag, "MainActivity-onTouchEvent-ACTION_DOWN...");
  21. break;
  22. case MotionEvent.ACTION_UP:
  23. Log.i(tag, "MainActivity-onTouchEvent-ACTION_UP...");
  24. break;
  25. default:break;
  26. }
  27. return super.onTouchEvent(event);
  28. }</span>

最终一次点击,打印信息如下:

Line 33: 01-08 14:59:45.847 I/yan     ( 4613): MainActivity-dispatchTouchEvent-ACTION_DOWN...
Line 35: 01-08 14:59:45.849 I/yan     ( 4613): TestButton-dispatchTouchEvent-ACTION_DOWN...
Line 37: 01-08 14:59:45.849 I/yan     ( 4613): testBtn-onTouch-ACTION_DOWN...
Line 39: 01-08 14:59:45.849 I/yan     ( 4613): TestButton-onTouchEvent-ACTION_DOWN...
Line 41: 01-08 14:59:45.939 I/yan     ( 4613): MainActivity-dispatchTouchEvent-ACTION_UP...
Line 43: 01-08 14:59:45.941 I/yan     ( 4613): TestButton-dispatchTouchEvent-ACTION_UP...
Line 45: 01-08 14:59:45.944 I/yan     ( 4613): testBtn-onTouch-ACTION_UP...
Line 47: 01-08 14:59:45.946 I/yan     ( 4613): TestButton-onTouchEvent-ACTION_UP...
Line 49: 01-08 14:59:45.974 I/yan     ( 4613): testBtn---onClick...
事件先由Activity的dispatchTouchEvent进行分发,然后TestButton的dispatchTouchEvent进行分发,接着执行onTouch监听,然后执行onTouchEvent。第二次UP动作的时候,在onTouchEvent里又执行了onClick监听。
如果我们想这个TestButton只能执行onTouch监听不能执行onClick监听,方法有很多。在onTouch监听里默认返回false改为true,如下:
[java] view plaincopy print?
  1. <span style="font-size:18px;">testBtn.setOnTouchListener(new View.OnTouchListener() {
  2. @Override
  3. public boolean onTouch(View v, MotionEvent event) {
  4. // TODO Auto-generated method stub
  5. switch(event.getAction()){
  6. case MotionEvent.ACTION_DOWN:
  7. Log.i(tag, "testBtn-onTouch-ACTION_DOWN...");
  8. break;
  9. case MotionEvent.ACTION_UP:
  10. Log.i(tag, "testBtn-onTouch-ACTION_UP...");
  11. break;
  12. default:break;
  13. }
  14. return true;
  15. }
  16. });</span>

事件流程为:

Line 75: 01-08 15:05:51.627 I/yan     ( 5262): MainActivity-dispatchTouchEvent-ACTION_DOWN...
Line 77: 01-08 15:05:51.628 I/yan     ( 5262): TestButton-dispatchTouchEvent-ACTION_DOWN...
Line 79: 01-08 15:05:51.629 I/yan     ( 5262): testBtn-onTouch-ACTION_DOWN...
Line 81: 01-08 15:05:51.689 I/yan     ( 5262): MainActivity-dispatchTouchEvent-ACTION_UP...
Line 83: 01-08 15:05:51.691 I/yan     ( 5262): TestButton-dispatchTouchEvent-ACTION_UP...
Line 85: 01-08 15:05:51.695 I/yan     ( 5262): testBtn-onTouch-ACTION_UP...
可以看到压根就没执行onTouchEvent。因为onTouch返回了true,已提前将这个事件消费了,就不往下传了,dispatch流程提前终止。

二、ViewGroup的dispatchTouchEvent、onInterceptTouchEvent、onTouchEvent

再来看ViewGroup,在复写ViewGroup时可以发现它的onTouchEvent在在View里的,表示这两个方法是一样的。但dispatchTouchEvent是在ViewGroup里的,表示和View的dispatchTouchEvent不一样,多了一个onInterceptTouchEvent函数,表示拦截的意思。链接 打个很形象的比喻,这玩意就像个秘书、谋士。为啥View没有呢,因为它级别不够,一个Button里面是不可能有子View的。但LinearLayout(继承ViewGroup)就有孩子(子布局),这个onInterceptTouchEvent就会判断事件要不要通知它的孩子呢。它的源码如下:
[java] view plaincopy print?
  1. <span style="font-size:18px;">    public boolean dispatchTouchEvent(MotionEvent ev) {
  2. if (mInputEventConsistencyVerifier != null) {
  3. mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
  4. }
  5. boolean handled = false;
  6. if (onFilterTouchEventForSecurity(ev)) {
  7. final int action = ev.getAction();
  8. final int actionMasked = action & MotionEvent.ACTION_MASK;
  9. // Handle an initial down.
  10. if (actionMasked == MotionEvent.ACTION_DOWN) {
  11. // Throw away all previous state when starting a new touch gesture.
  12. // The framework may have dropped the up or cancel event for the previous gesture
  13. // due to an app switch, ANR, or some other state change.
  14. cancelAndClearTouchTargets(ev);
  15. resetTouchState();
  16. }
  17. // Check for interception.
  18. final boolean intercepted;
  19. if (actionMasked == MotionEvent.ACTION_DOWN
  20. || mFirstTouchTarget != null) {
  21. final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
  22. if (!disallowIntercept) {
  23. <strong><span style="color:#ff0000;">intercepted = onInterceptTouchEvent(ev);</span></strong>
  24. ev.setAction(action); // restore action in case it was changed
  25. } else {
  26. intercepted = false;
  27. }
  28. } else {
  29. // There are no touch targets and this action is not an initial down
  30. // so this view group continues to intercept touches.
  31. intercepted = true;
  32. }
  33. // Check for cancelation.
  34. final boolean canceled = resetCancelNextUpFlag(this)
  35. || actionMasked == MotionEvent.ACTION_CANCEL;
  36. // Update list of touch targets for pointer down, if needed.
  37. final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;
  38. TouchTarget newTouchTarget = null;
  39. boolean alreadyDispatchedToNewTouchTarget = false;
  40. <strong><span style="color:#ff0000;">if (!canceled && !intercepted)</span></strong> {
  41. if (actionMasked == MotionEvent.ACTION_DOWN
  42. || (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)
  43. || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
  44. final int actionIndex = ev.getActionIndex(); // always 0 for down
  45. final int idBitsToAssign = split ? 1 << ev.getPointerId(actionIndex)
  46. : TouchTarget.ALL_POINTER_IDS;
  47. // Clean up earlier touch targets for this pointer id in case they
  48. // have become out of sync.
  49. removePointersFromTouchTargets(idBitsToAssign);
  50. final int childrenCount = mChildrenCount;
  51. if (childrenCount != 0) {
  52. // Find a child that can receive the event.
  53. // Scan children from front to back.
  54. final View[] children = mChildren;
  55. final float x = ev.getX(actionIndex);
  56. final float y = ev.getY(actionIndex);
  57. final boolean customOrder = isChildrenDrawingOrderEnabled();
  58. for (int i = childrenCount - 1; i >= 0; i--) {
  59. final int childIndex = customOrder ?
  60. getChildDrawingOrder(childrenCount, i) : i;
  61. final View child = children[childIndex];
  62. if (!canViewReceivePointerEvents(child)
  63. || !isTransformedTouchPointInView(x, y, child, null)) {
  64. continue;
  65. }
  66. newTouchTarget = getTouchTarget(child);
  67. if (newTouchTarget != null) {
  68. // Child is already receiving touch within its bounds.
  69. // Give it the new pointer in addition to the ones it is handling.
  70. newTouchTarget.pointerIdBits |= idBitsToAssign;
  71. break;
  72. }
  73. resetCancelNextUpFlag(child);
  74. if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
  75. // Child wants to receive touch within its bounds.
  76. mLastTouchDownTime = ev.getDownTime();
  77. mLastTouchDownIndex = childIndex;
  78. mLastTouchDownX = ev.getX();
  79. mLastTouchDownY = ev.getY();
  80. newTouchTarget = addTouchTarget(child, idBitsToAssign);
  81. alreadyDispatchedToNewTouchTarget = true;
  82. break;
  83. }
  84. }
  85. }
  86. if (newTouchTarget == null && mFirstTouchTarget != null) {
  87. // Did not find a child to receive the event.
  88. // Assign the pointer to the least recently added target.
  89. newTouchTarget = mFirstTouchTarget;
  90. while (newTouchTarget.next != null) {
  91. newTouchTarget = newTouchTarget.next;
  92. }
  93. newTouchTarget.pointerIdBits |= idBitsToAssign;
  94. }
  95. }
  96. }
  97. // Dispatch to touch targets.
  98. if (mFirstTouchTarget == null) {
  99. // No touch targets so treat this as an ordinary view.
  100. handled = dispatchTransformedTouchEvent(ev, canceled, null,
  101. TouchTarget.ALL_POINTER_IDS);
  102. } else {
  103. // Dispatch to touch targets, excluding the new touch target if we already
  104. // dispatched to it.  Cancel touch targets if necessary.
  105. TouchTarget predecessor = null;
  106. TouchTarget target = mFirstTouchTarget;
  107. while (target != null) {
  108. final TouchTarget next = target.next;
  109. if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
  110. handled = true;
  111. } else {
  112. final boolean cancelChild = resetCancelNextUpFlag(target.child)
  113. || intercepted;
  114. if (dispatchTransformedTouchEvent(ev, cancelChild,
  115. target.child, target.pointerIdBits)) {
  116. handled = true;
  117. }
  118. if (cancelChild) {
  119. if (predecessor == null) {
  120. mFirstTouchTarget = next;
  121. } else {
  122. predecessor.next = next;
  123. }
  124. target.recycle();
  125. target = next;
  126. continue;
  127. }
  128. }
  129. predecessor = target;
  130. target = next;
  131. }
  132. }
  133. // Update list of touch targets for pointer up or cancel, if needed.
  134. if (canceled
  135. || actionMasked == MotionEvent.ACTION_UP
  136. || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
  137. resetTouchState();
  138. } else if (split && actionMasked == MotionEvent.ACTION_POINTER_UP) {
  139. final int actionIndex = ev.getActionIndex();
  140. final int idBitsToRemove = 1 << ev.getPointerId(actionIndex);
  141. removePointersFromTouchTargets(idBitsToRemove);
  142. }
  143. }
  144. if (!handled && mInputEventConsistencyVerifier != null) {
  145. mInputEventConsistencyVerifier.onUnhandledEvent(ev, 1);
  146. }
  147. return handled;
  148. }</span>

可以看到标红的有两句(intercepted = onInterceptTouchEvent(ev);    if (!canceled && !intercepted)  ),它会先调用 intercepted = onInterceptTouchEvent(ev);然后通过if判断。

[java] view plaincopy print?
  1. <span style="font-size:18px;">  public boolean onInterceptTouchEvent(MotionEvent ev) {
  2. return false;
  3. }</span>

它就一句话,默认false。也就是说这个谋士默认的意见是,永远不拦截!!!!只要有孩子,就交给孩子们处理吧。下面给出实例说明,新建TestLinearLayout继承自Linearlayout。

[java] view plaincopy print?
  1. <span style="font-size:18px;">package org.yanzi.ui;
  2. import android.content.Context;
  3. import android.util.AttributeSet;
  4. import android.util.Log;
  5. import android.view.MotionEvent;
  6. import android.widget.LinearLayout;
  7. public class TestLinearLayout extends LinearLayout{
  8. private final static String tag = "yan";
  9. public TestLinearLayout(Context context, AttributeSet attrs) {
  10. super(context, attrs);
  11. // TODO Auto-generated constructor stub
  12. }
  13. @Override
  14. public boolean dispatchTouchEvent(MotionEvent ev) {
  15. // TODO Auto-generated method stub
  16. switch(ev.getAction()){
  17. case MotionEvent.ACTION_DOWN:
  18. Log.i(tag, "TestLinearLayout-dispatchTouchEvent-ACTION_DOWN...");
  19. break;
  20. case MotionEvent.ACTION_UP:
  21. Log.i(tag, "TestLinearLayout-dispatchTouchEvent-ACTION_UP...");
  22. break;
  23. default:break;
  24. }
  25. return super.dispatchTouchEvent(ev);
  26. }
  27. @Override
  28. public boolean onInterceptTouchEvent(MotionEvent ev) {
  29. // TODO Auto-generated method stub
  30. switch(ev.getAction()){
  31. case MotionEvent.ACTION_DOWN:
  32. Log.i(tag, "TestLinearLayout-onInterceptTouchEvent-ACTION_DOWN...");
  33. break;
  34. case MotionEvent.ACTION_UP:
  35. Log.i(tag, "TestLinearLayout-onInterceptTouchEvent-ACTION_UP...");
  36. break;
  37. default:break;
  38. }
  39. return super.onInterceptTouchEvent(ev);
  40. }
  41. @Override
  42. public boolean onTouchEvent(MotionEvent event) {
  43. // TODO Auto-generated method stub
  44. switch(event.getAction()){
  45. case MotionEvent.ACTION_DOWN:
  46. Log.i(tag, "TestLinearLayout-onTouchEvent-ACTION_DOWN...");
  47. break;
  48. case MotionEvent.ACTION_UP:
  49. Log.i(tag, "TestLinearLayout-onTouchEvent-ACTION_UP...");
  50. break;
  51. default:break;
  52. }
  53. return super.onTouchEvent(event);
  54. }
  55. }
  56. </span>

布局文件改成:

[html] view plaincopy print?
  1. <span style="font-size:18px;"><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. xmlns:tools="http://schemas.android.com/tools"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:paddingBottom="@dimen/activity_vertical_margin"
  6. android:paddingLeft="@dimen/activity_horizontal_margin"
  7. android:paddingRight="@dimen/activity_horizontal_margin"
  8. android:paddingTop="@dimen/activity_vertical_margin"
  9. tools:context=".MainActivity" >
  10. <TextView
  11. android:layout_width="wrap_content"
  12. android:layout_height="wrap_content"
  13. android:text="@string/hello_world" />
  14. <org.yanzi.ui.TestLinearLayout
  15. android:id="@+id/linearlayout_test"
  16. android:layout_width="200dip"
  17. android:layout_height="200dip" >
  18. <org.yanzi.ui.TestButton
  19. android:id="@+id/btn_test"
  20. android:layout_width="wrap_content"
  21. android:layout_height="wrap_content"
  22. android:text="测试按钮" />
  23. </org.yanzi.ui.TestLinearLayout>
  24. </RelativeLayout></span>

在Activity里给这个自定义LinearLayout也注册上onClick监听、onTouch监听。

[java] view plaincopy print?
  1. <span style="font-size:18px;">testLinelayout = (TestLinearLayout)findViewById(R.id.linearlayout_test);
  2. testLinelayout.setOnTouchListener(new View.OnTouchListener() {
  3. @Override
  4. public boolean onTouch(View v, MotionEvent event) {
  5. // TODO Auto-generated method stub
  6. switch(event.getAction()){
  7. case MotionEvent.ACTION_DOWN:
  8. Log.i(tag, "testLinelayout-onTouch-ACTION_DOWN...");
  9. break;
  10. case MotionEvent.ACTION_UP:
  11. Log.i(tag, "testLinelayout-onTouch-ACTION_UP...");
  12. break;
  13. default:break;
  14. }
  15. return false;
  16. }
  17. });
  18. testLinelayout.setOnClickListener(new View.OnClickListener() {
  19. @Override
  20. public void onClick(View v) {
  21. // TODO Auto-generated method stub
  22. Log.i(tag, "testLinelayout---onClick...");
  23. }
  24. });</span>

不复写事件传递里的 任何方法,流程如下:

Line 57: 01-08 15:29:42.167 I/yan     ( 5826): MainActivity-dispatchTouchEvent-ACTION_DOWN...
Line 59: 01-08 15:29:42.169 I/yan     ( 5826): TestLinearLayout-dispatchTouchEvent-ACTION_DOWN...
Line 61: 01-08 15:29:42.169 I/yan     ( 5826): TestLinearLayout-onInterceptTouchEvent-ACTION_DOWN...
Line 63: 01-08 15:29:42.169 I/yan     ( 5826): TestButton-dispatchTouchEvent-ACTION_DOWN...
Line 65: 01-08 15:29:42.170 I/yan     ( 5826): testBtn-onTouch-ACTION_DOWN...
Line 67: 01-08 15:29:42.170 I/yan     ( 5826): TestButton-onTouchEvent-ACTION_DOWN...
---------------------------------------------------------------------------------------------------------------------------
Line 69: 01-08 15:29:42.279 I/yan     ( 5826): MainActivity-dispatchTouchEvent-ACTION_UP...
Line 71: 01-08 15:29:42.280 I/yan     ( 5826): TestLinearLayout-dispatchTouchEvent-ACTION_UP...
Line 73: 01-08 15:29:42.283 I/yan     ( 5826): TestLinearLayout-onInterceptTouchEvent-ACTION_UP...
Line 75: 01-08 15:29:42.287 I/yan     ( 5826): TestButton-dispatchTouchEvent-ACTION_UP...
Line 81: 01-08 15:29:42.298 I/yan     ( 5826): testBtn-onTouch-ACTION_UP...
Line 83: 01-08 15:29:42.301 I/yan     ( 5826): TestButton-onTouchEvent-ACTION_UP...
Line 85: 01-08 15:29:42.313 I/yan     ( 5826): testBtn---onClick...
由Activity的dispatchTouchEvent----Linearlayout的dispatchTouchEvent------------问问它的谋士要不要让孩子知道onInterceptTouchEvent---------孩子的dispatchTouchEvent-----孩子的onTouch监听------孩子的onTouchEvent----孩子的onClick监听。为了更清晰这个流程,下面作如下改动:
1、如果事件传给了孩子们,但孩子没有onTouch和onClick监听怎么办?即将button的onclick和onTouch都注释掉:
流程如下:
Line 131: 01-08 15:36:16.574 I/yan     ( 6124): TestLinearLayout-dispatchTouchEvent-ACTION_DOWN...
Line 133: 01-08 15:36:16.574 I/yan     ( 6124): TestLinearLayout-onInterceptTouchEvent-ACTION_DOWN...
Line 135: 01-08 15:36:16.574 I/yan     ( 6124): TestButton-dispatchTouchEvent-ACTION_DOWN...
Line 137: 01-08 15:36:16.575 I/yan     ( 6124): TestButton-onTouchEvent-ACTION_DOWN...
Line 143: 01-08 15:36:16.746 I/yan     ( 6124): MainActivity-dispatchTouchEvent-ACTION_UP...
Line 145: 01-08 15:36:16.747 I/yan     ( 6124): TestLinearLayout-dispatchTouchEvent-ACTION_UP...
Line 147: 01-08 15:36:16.747 I/yan     ( 6124): TestLinearLayout-onInterceptTouchEvent-ACTION_UP...
Line 149: 01-08 15:36:16.748 I/yan     ( 6124): TestButton-dispatchTouchEvent-ACTION_UP...
Line 151: 01-08 15:36:16.748 I/yan     ( 6124): TestButton-onTouchEvent-ACTION_UP...
因为事件给了孩子们,它没监听也关系不到父亲了,父亲的onClick和onTouch都没执行。
2,如果将TestLinearlayout的onInterceptTouchEvent 改成return true,即不让孩子们知道。
Line 57: 01-08 15:40:06.832 I/yan     ( 6640): MainActivity-dispatchTouchEvent-ACTION_DOWN...
Line 59: 01-08 15:40:06.835 I/yan     ( 6640): TestLinearLayout-dispatchTouchEvent-ACTION_DOWN...
Line 61: 01-08 15:40:06.836 I/yan     ( 6640): TestLinearLayout-onInterceptTouchEvent-ACTION_DOWN...
Line 63: 01-08 15:40:06.836 I/yan     ( 6640): testLinelayout-onTouch-ACTION_DOWN...
Line 65: 01-08 15:40:06.836 I/yan     ( 6640): TestLinearLayout-onTouchEvent-ACTION_DOWN...
Line 67: 01-08 15:40:07.016 I/yan     ( 6640): MainActivity-dispatchTouchEvent-ACTION_UP...
Line 69: 01-08 15:40:07.017 I/yan     ( 6640): TestLinearLayout-dispatchTouchEvent-ACTION_UP...
Line 73: 01-08 15:40:07.025 I/yan     ( 6640): testLinelayout-onTouch-ACTION_UP...
Line 75: 01-08 15:40:07.026 I/yan     ( 6640): TestLinearLayout-onTouchEvent-ACTION_UP...
Line 77: 01-08 15:40:07.052 I/yan     ( 6640): testLinelayout---onClick...
果然事件就此打住,孩子们压根不知道,父亲执行了onClick和onTouch监听。可见父亲还是伟大的啊,只要谋士不拦截事件,那么事件就给孩子。
最后的结论:
1、如果是自定义复合控件,如图片+文字,我再Activity里给你注册了onClick监听,期望点击它执行。那么最简单的方法就是将图片+文字的父布局,也即让其容器ViewGroup的秘书将事件拦下,这样父亲就可以执行onClick了。这时候的父亲就像一个独立的孩子一样了(View),无官一身轻,再也不用管它的孩子了,可以正常onClick onTouch.
2、如果希望一个View只onTouch而不onClick,在onTouch里return true就ok了。
3、dispatch是为了onTouch监听,onTouchEvent是为了onClick监听。
4、自定义布局时,一般情况下:
@Override
public boolean onTouchEvent(MotionEvent event) {return super.onTouchEvent(event);}  
@Override
public boolean dispatchTouchEvent(MotionEvent event) {return super.dispatchTouchEvent(event);
我们可以复写,但是最后的super.***是万万不能少滴。如果少了,表示连dispatch*** onTouchEvent压根就不调用了,事件就此打住。
貌似真相水落石出了,但究竟清楚了没有请看下篇根据自定义复合控件的监听问题再探讨下。

细说Android事件传递相关推荐

  1. android touch机制,细说Android事件传递机制(dispatchTouchEvent、onInterceptTouchEvent、onTouchEvent)...

    本文背景:前些天用到了之前写的自定义图片文字复合控件,在给他设置监听时遇到了麻烦.虽然最后解决了问题,但发现在不重写LinearLayout的onInterceptTouchEvent时,子Image ...

  2. Android事件传递机制(转)

    Android事件构成 在Android中,事件主要包括点按.长按.拖拽.滑动等,点按又包括单击和双击,另外还包括单指操作和多指操作.所有这些都构成了Android中的事件响应.总的来说,所有的事件都 ...

  3. android imageview 事件传递,Android 事件传递机制TextView,ImageView等没有默认clickable属性的View单独设置onTouch事件注意事项...

    本文讲解TextView,ImageView等没有默认clickable属性的View单独设置onTouch事件 Android 事件传递机制:Android 事件传递机制初涉 我们知道 Button ...

  4. Android 事件传递机制总结

    Android 事件传递机制总结 Android View虽然不是四大组件,但是其重要程度堪比四大组件.初级工程师到中高级工程师,这些都是很重要的,因为事件分发机制面试也会经常被提及,如果我们能get ...

  5. android 时间传递,Android事件传递

    事件经过主要的三层,分别是Activity.Layout(多个).View 三者都拥有dispatchTouchEvent和onTouchEvent方法. dispatchTouchEvent是用来控 ...

  6. Android事件传递(分发)机制

    Android事件的构成: 在android中,事件主要包括点按,长按,拖拽,滑动等等,另外点按还包括点击和双击.所有这些都构成了android中的事件响应.总的来说所有的事件都由以下三个部分组成: ...

  7. Android事件传递机制【Touch事件】

    Android中提供了ViewGroup.View.Activity三个等级的Touch事件处理.也就是说,这三个地方都有事件回调方法. 测试DEMO视图结构: <com .orgcent.ev ...

  8. Android事件传递简单分析

    1.Activity事件处理 package com.example.eventdemo01;import androidx.appcompat.app.AppCompatActivity;impor ...

  9. Android事件传递可以这样理解

    前言 关于Android中事件传递机制早已是老生常谈的话题,甭管工作多久水平咋样应该都能道出一二.依稀记得刚接触事件分发那会,一股脑的钻进网络上那几张神图,什么三大方法.职责链,最后再巴拉巴拉贴一大堆 ...

最新文章

  1. E667:Fsync failed(how to solve)
  2. Java-学习笔记-1-概述
  3. python ctypes库中动态链接库加载方式
  4. everytime you write on a whiteboard
  5. KineticJS教程(6)
  6. 上海交大计算机学院奖学金,上海交通大学-电子信息与电气工程学院-学生工作办公室...
  7. 纽微特记事:发火说产品差,业务开展不了,怎么不找自已的问题
  8. 一年级下册健康教育教案
  9. 解决Hash冲突四种方法
  10. macd柱体和汇价的背离
  11. Excel_一维二维表转换(行列转换)的几种方法
  12. dreamweaver cs6 html5 pack,HTML5 Pack for Dreamweaver CS5——HTML5开发工具
  13. Android 自动朗读TT
  14. b250支持服务器cpu,b250m主板上什么cpu
  15. 设置Windows Server登录时禁止自动启动服务器管理器
  16. scaling之旅_【scaling】什么意思_英语scaling的翻译_音标_读音_用法_例句_在线翻译_有道词典...
  17. 示波器的使用及其原理
  18. FDC2214 手势识别方案 以及设计大致流程
  19. TortoiseSVN (Subversion客户端) 使用手册(中文) (六)
  20. STemWin学习:关于窗口消息的基础知识

热门文章

  1. LeetCode 232. Implement Queue using Stacks--用2个栈来实现一个队列--C++解法
  2. 女朋友求爱c语言程序,[转载]一个程序员写的求爱程序
  3. linux mysql 5.0.45_RedHat糸列Mysql-5.0.45的安装
  4. php html 变量,PHP与HTML混编,使用PHP变量代替数据--20190221
  5. 中国有神经网络计算机,新神经网络使计算机像人一样推理
  6. linux cache控制 内核,linux内核之bcache简介 [转]
  7. 五大点,搞懂单线程的Redis到底快在哪里
  8. spring mvc基本概念
  9. iOS使用Workspace来管理多项目
  10. java不同的数据源如何处理_java – 如何在不同的数据源上创建两个类之间的关系?...