Android中onInterceptTouchEvent、dispatchTouchEvent及onTouchEvent的调用顺序及内部原理

在Android中需要经常对用户手势进行判断,在判断手势时需要精细的分清楚每个触摸事件以及每个View对事件的接收情况,在View,ViewGroup,Activity中都可以接收事件,在对事件进行处理时onInterceptTouchEvent、dispatchTouchEvent及onTouchEvent这三个函数的调用顺序及关系需要好好理清楚。原理代码有点多,如果不对着具体事例,理解起来很难。下面对着代码进行分析。代码地址为:https://github.com/huangtianyu/DispatchTouchEvent,记得帮忙点Star

MainActivity.java

  1. package com.zqc.dispatchtouchevent;  
  2.   
  3. import android.app.Activity;  
  4. import android.os.Bundle;  
  5. import android.util.Log;  
  6. import android.view.MotionEvent;  
  7. import android.view.View;  
  8.   
  9. import static com.zqc.dispatchtouchevent.Constants.TAG;  
  10.   
  11. public class MainActivity extends Activity implements View.OnTouchListener {  
  12.     private MyView myView;  
  13.     @Override  
  14.     protected void onCreate(Bundle savedInstanceState) {  
  15.         super.onCreate(savedInstanceState);  
  16.         Log.e(TAG, "MainActivity onCreate");  
  17.         setContentView(R.layout.activity_main);  
  18.         myView = (MyView) findViewById(R.id.myview);  
  19.         myView.setOnTouchListener(MainActivity.this);  
  20.     }  
  21.     @Override  
  22.     public boolean dispatchTouchEvent(MotionEvent ev) {  
  23.         Log.e(TAG, "MainActivity dispatchTouchEvent");  
  24.         return super.dispatchTouchEvent(ev);  
  25.     }  
  26.     @Override  
  27.     public boolean onTouchEvent(MotionEvent event) {  
  28.         Log.e(TAG, "MainActivity onTouchEvent");  
  29.         switch (event.getAction()) {  
  30.             case MotionEvent.ACTION_DOWN:  
  31.                 Log.e(TAG, "MainActivity onTouchEvent ACTION_DOWN");  
  32.                 break;  
  33.             case MotionEvent.ACTION_MOVE:  
  34.                 Log.e(TAG, "MainActivity onTouchEvent ACTION_MOVE");  
  35.                 break;  
  36.             case MotionEvent.ACTION_CANCEL:  
  37.                 Log.e(TAG, "MainActivity onTouchEvent ACTION_CANCEL");  
  38.                 break;  
  39.             case MotionEvent.ACTION_UP:  
  40.                 Log.e(TAG, "MainActivity onTouchEvent ACTION_UP");  
  41.                 break;  
  42.             default:  
  43.                 Log.e(TAG, "MainActivity onTouchEvent " + event.getAction());  
  44.                 break;  
  45.         }  
  46.         return super.onTouchEvent(event);  
  47.     }  
  48.     @Override  
  49.     protected void onResume() {  
  50.         Log.e(TAG, "MainActivity onResume");  
  51.         super.onResume();  
  52.     }  
  53.     @Override  
  54.     protected void onPause() {  
  55.         Log.e(TAG, "MainActivity onPause");  
  56.         super.onPause();  
  57.     }  
  58.     @Override  
  59.     public boolean onTouch(View v, MotionEvent event) {  
  60.         Log.e(TAG, "MainActivity onTouch");  
  61.         switch (event.getAction() & MotionEvent.ACTION_MASK) {  
  62.             case MotionEvent.ACTION_DOWN:  
  63.                 Log.e(TAG, "MainActivity onTouch ACTION_DOWN");  
  64.                 break;  
  65.             case MotionEvent.ACTION_MOVE:  
  66.                 Log.e(TAG, "MainActivity onTouch ACTION_MOVE");  
  67.                 break;  
  68.             case MotionEvent.ACTION_CANCEL:  
  69.                 Log.e(TAG, "MainActivity onTouch ACTION_CANCEL");  
  70.                 break;  
  71.             case MotionEvent.ACTION_UP:  
  72.                 Log.e(TAG, "MainActivity onTouch ACTION_UP");  
  73.                 break;  
  74.             default:  
  75.                 Log.e(TAG, "MainActivity onTouchEvent " + event.getAction());  
  76.                 break;  
  77.         }  
  78.         return false;  
  79.     }  
  80. }  

MyView.java

  1. package com.zqc.dispatchtouchevent;  
  2.   
  3. import android.content.Context;  
  4. import android.util.AttributeSet;  
  5. import android.util.Log;  
  6. import android.view.GestureDetector;  
  7. import android.view.MotionEvent;  
  8. import android.widget.TextView;  
  9.   
  10. import static com.zqc.dispatchtouchevent.Constants.MY_GESTURE_TAG;  
  11. import static com.zqc.dispatchtouchevent.Constants.TAG;  
  12.   
  13.   
  14. public class MyView extends TextView {  
  15.     private Context mContext;  
  16.     //private GestureDetector mGesture;  
  17.   
  18.     public MyView(Context context) {  
  19.         this(context, null);  
  20.     }  
  21.   
  22.     public MyView(Context context, AttributeSet attrs) {  
  23.         super(context, attrs);  
  24.         Log.e(TAG, "MyView");  
  25.         mContext = context;  
  26.         //手势初始化  
  27.        // mGesture = new GestureDetector(mContext, mGestureListener);  
  28.     }  
  29.   
  30.     @Override  
  31.     public boolean onTouchEvent(MotionEvent event) {  
  32.         Log.e(TAG, "MyView onTouchEvent");  
  33.         switch (event.getAction()) {  
  34.             case MotionEvent.ACTION_DOWN:  
  35.                 Log.e(TAG, "MyView onTouchEvent ACTION_DOWN");  
  36.                 break;  
  37.             case MotionEvent.ACTION_MOVE:  
  38.                 Log.e(TAG, "MyView onTouchEvent ACTION_MOVE");  
  39.                 break;  
  40.             case MotionEvent.ACTION_CANCEL:  
  41.                 Log.e(TAG, "MyView onTouchEvent ACTION_CANCEL");  
  42.                 break;  
  43.             case MotionEvent.ACTION_UP:  
  44.                 Log.e(TAG, "MyView onTouchEvent ACTION_UP");  
  45.                 break;  
  46.             default:  
  47.                 Log.e(TAG, "MyView onTouchEvent " + event.getAction());  
  48.                 break;  
  49.         }  
  50. //        设置手势监听  
  51.        // mGesture.onTouchEvent(event);  
  52.         return super.onTouchEvent(event);  
  53.     }  
  54.   
  55.     @Override  
  56.     public boolean dispatchTouchEvent(MotionEvent event) {  
  57.         Log.e(TAG, "MyView dispatchTouchEvent");  
  58.         return super.dispatchTouchEvent(event);  
  59.     }  
  60. }  

MyViewGroup.java

  1. package com.zqc.dispatchtouchevent;  
  2.   
  3. import android.content.Context;  
  4. import android.util.AttributeSet;  
  5. import android.util.Log;  
  6. import android.view.MotionEvent;  
  7. import android.widget.RelativeLayout;  
  8.   
  9. import static com.zqc.dispatchtouchevent.Constants.TAG;  
  10.   
  11. public class MyViewGroup extends RelativeLayout {  
  12.     public MyViewGroup(Context context) {  
  13.         this(context, null);  
  14.     }  
  15.   
  16.     public MyViewGroup(Context context, AttributeSet attrs) {  
  17.         super(context, attrs);  
  18.         Log.e(TAG, "MyViewGroup");  
  19.     }  
  20.   
  21.     @Override  
  22.     public boolean onInterceptTouchEvent(MotionEvent ev) {  
  23.         Log.e(TAG, "MyViewGroup onInterceptTouchEvent");  
  24.         return super.onInterceptTouchEvent(ev);  
  25.     }  
  26.   
  27.     @Override  
  28.     public boolean dispatchTouchEvent(MotionEvent ev) {  
  29.         Log.e(TAG, "MyViewGroup dispatchTouchEvent");  
  30.         return super.dispatchTouchEvent(ev);  
  31.     }  
  32.   
  33.     @Override  
  34.     public boolean onTouchEvent(MotionEvent event) {  
  35.         Log.e(TAG, "MyViewGroup onTouchEvent");  
  36.         switch (event.getAction()) {  
  37.             case MotionEvent.ACTION_DOWN:  
  38.                 Log.e(TAG, "MyViewGroup onTouchEvent ACTION_DOWN");  
  39.                 break;  
  40.             case MotionEvent.ACTION_MOVE:  
  41.                 Log.e(TAG, "MyViewGroup onTouchEvent ACTION_MOVE");  
  42.                 break;  
  43.             case MotionEvent.ACTION_CANCEL:  
  44.                 Log.e(TAG, "MyViewGroup onTouchEvent ACTION_CANCEL");  
  45.                 break;  
  46.             case MotionEvent.ACTION_UP:  
  47.                 Log.e(TAG, "MyViewGroup onTouchEvent ACTION_UP");  
  48.                 break;  
  49.             default:  
  50.                 Log.e(TAG, "MyViewGroup onTouchEvent " + event.getAction());  
  51.                 break;  
  52.         }  
  53.         return super.onTouchEvent(event);  
  54.     }  
  55. }  

Contants.java

  1. package com.zqc.dispatchtouchevent;  
  2.   
  3. public class Constants {  
  4.   
  5.     public final static String TAG = "MY_LOG";  
  6.     public final static String MY_GESTURE_TAG = "GESTURE_TAG";  
  7. }  

在代码中将每个函数分别列出并加上Log输出,这样对着Log日志进行分析,则一目了然。

1.让所有的onInterceptTouchEvent、dispatchTouchEvent及onTouchEvent均返回super.onTouchEvent即均返回false时,轻轻点击MyView然后快速抬起,查看相应的Log:

 

通过Log能清楚的查看代码执行的流程,具体流程如下:

DOWN事件:MainActivity.dispatchTouchEvent->MyViewGroup.dispatchTouchEvet->MyViewGroup.onInterceptTouchEvent->MyView.dispatchTouchEvent->setOnTouchListener.onTouch->MyView.onTouchEvent->MyViewGroup.onTouchEvent->MainActivity.onTouchEvent

UP事件:MainActivity.dispatchTouchEvent->MainActivity.onTouchEvent

从上面流程可以看出,点击事件最先传给窗口Activity的dispatchTouchEvent函数进行事件分发,然后对于View类,是先传给对应的父View的dispatchTouchEvent进行事件分发,然后在传给里面点击的View。当down事件没有被各个view消费时,最终会调用Acitivity的onTouchEvent,并在在Down后续的UP事件不在传给MyViewGroup和MyView,直接传给MainAcitivity。所以当事件没有被窗口中的View消费时,最终都是给了该窗口Activity类中的onTouchEvent事件处理。从Log中也可以看出setOnTouchListener中的onTouch事件是在对应View的onTouchEvent事件之前被执行。

2.当MainAcivity中dispathTouchEvent返回true时,轻轻点击MyView,查看对应Log:

通过Log可以看到当窗口Activity的dispatchTouchEvent返回true时,DOWN事件没有往View中传,也就没有调用任何的onTouchEvent事件,UP事件也是走到Activity的dispatchTouchEvent时也就结束了。

3.重新置Activity中dispatchTouchEvent返回false,然后置ViewGroup中onInterceptTouchEvent返回true时,轻轻点击MyView查看对应Log:

这时DOWN事件和UP事件的执行流程如下:

DOWN事件:MainActivity.dipatchTouchEvent->MyViewGroup.dispatchTouchEvent->MyViewGroup.onInterceptTouchEvent->MyViewGroup.onTouchEvent->MainActivity.onTouchEvent.

UP事件:MainActiviy.dispatchTouchEvent->MainActivity.onTouchEvent.

从Log中可以看出,当onInterceptTouchEvent返回true时,事件即被MyViewGroup拦截了,这时事件就直接传给MyViewGroup.onTouchEvent,不在往子View传,由于MyViewGroup.onTouchEvent返回的是false,即MyViewGroup并没有消费事件,这时事件会传给窗口Activity,UP事件会传给最后一个接受Down事件的窗口或View。

4.当MyView中onTouchEvent返回true时,即MyView会消费传给他的事件。轻点MyView查看对应的Log:


继续分析DOWN事件的流程:

DOWN事件:MainActivity.dispatchTouchEvent->MyViewGroup.dispatchTouchEvet->MyViewGroup.onInterceptTouchEvent->MyView.dispatchTouchEvent->setOnTouchListener.onTouch->MyView.onTouchEvent

UP事件:MainActivity.dispatchTouchEvent->MyViewGroup.dispatchTouchEvet->MyViewGroup.onInterceptTouchEvent->MyView.dispatchTouchEvent->setOnTouchListener.onTouch->MyView.onTouchEvent

从上面的执行流程可以看出当事件被MyView消费后,事件不会在往上传,后续的UP事件也直接通过dispatchTouchEvent分发给对应的View,这里还是提一下,在MainAcitivy中设置的setOnTouchListener中的onTouch事件是在MyView自身的onTouchEvent事件之前被执行,因而设置的setOnTouchEvent的onTouch函数还是会被执行。

先只分析这几种场景,MOVE事件和UP事件一样只要DOWN事件被某个View消耗了,那么MOVE事件也就直接传到这个View。可以下载代码运行后,在MyView上面滑动下看下Log,具体Log我也贴一份。

情况1:

情况2:

下面对着Android源码来具体分析View的触摸事件到底是怎么执行的。首先根据Log可以最先接收到消息的是Activity的dispatchTouchEvent,在该处设置断点,然后查看对应的调用方法栈(你会发现在调到MainActivity的dispatchTouchEvent时,前面已经调用了很多方法),如下:

由于Android系统启动后会先启动Zygote进程,该进程会在手机开机后一直运行,Android中的几个系统服务都是由Zygote进程fork出来的,一个应用在启动时所分配到的进程也是由Zygote进程fork出来的,通常说一个应用的起点是Application里面的onCreate函数,其实真正的起点是ActivityThread里面的main函数,看到这个main函数是不是有种熟悉的感觉啊。在main函数中初始化了应用程序的主线程,同时初始化了主线程的消息队列,并调用了Looper.loop()函数使主线程不断的对消息队列进行循环检测,有消息则进行处理。点击事件产生一个消息,该消息传到InputEventReceiver后,由InputEventReceiver的继承类WindowInputEventReceiver去处理,WindowInputEventReceiver类是ViewRootImpl类的内部类,查看对应代码如下:

ViewRootImpl.java

  1. final class WindowInputEventReceiver extends InputEventReceiver {  
  2.     public WindowInputEventReceiver(InputChannel inputChannel, Looper looper) {  
  3.         super(inputChannel, looper);  
  4.     }  
  5.   
  6.     @Override  
  7.     public void onInputEvent(InputEvent event) {  
  8.         enqueueInputEvent(event, this, 0, true);  
  9.     }  
  10.   
  11.     @Override  
  12.     public void onBatchedInputEventPending() {  
  13.         if (mUnbufferedInputDispatch) {  
  14.             super.onBatchedInputEventPending();  
  15.         } else {  
  16.             scheduleConsumeBatchedInput();  
  17.         }  
  18.     }  
  19.   
  20.     @Override  
  21.     public void dispose() {  
  22.         unscheduleConsumeBatchedInput();  
  23.         super.dispose();  
  24.     }  
  25. }  

查看代码可以当点击消息过来时,直接调用ViewRootImpl类中的enqueueInputEvent(event,this,0,true)方法:

ViewRootImpl.java

  1. void enqueueInputEvent(InputEvent event,  
  2.         InputEventReceiver receiver, int flags, boolean processImmediately) {  
  3.     adjustInputEventForCompatibility(event);  
  4.     QueuedInputEvent q = obtainQueuedInputEvent(event, receiver, flags);  
  5.   
  6.     // Always enqueue the input event in order, regardless of its time stamp.  
  7.     // We do this because the application or the IME may inject key events  
  8.     // in response to touch events and we want to ensure that the injected keys  
  9.     // are processed in the order they were received and we cannot trust that  
  10.     // the time stamp of injected events are monotonic.  
  11.     QueuedInputEvent last = mPendingInputEventTail;  
  12.     if (last == null) {  
  13.         mPendingInputEventHead = q;  
  14.         mPendingInputEventTail = q;  
  15.     } else {  
  16.         last.mNext = q;  
  17.         mPendingInputEventTail = q;  
  18.     }  
  19.     mPendingInputEventCount += 1;  
  20.     Trace.traceCounter(Trace.TRACE_TAG_INPUT, mPendingInputEventQueueLengthCounterName,  
  21.             mPendingInputEventCount);  
  22.   
  23.     if (processImmediately) {  
  24.         doProcessInputEvents();  
  25.     } else {  
  26.         scheduleProcessInputEvents();  
  27.     }  
  28. }  

由于processImmediately为true,因而是立即处理,即直接调用doProcessInputEvents();

ViewRootImpl.java

  1. void doProcessInputEvents() {  
  2.     // Deliver all pending input events in the queue.  
  3.     while (mPendingInputEventHead != null) {  
  4.         QueuedInputEvent q = mPendingInputEventHead;  
  5.         mPendingInputEventHead = q.mNext;  
  6.         if (mPendingInputEventHead == null) {  
  7.             mPendingInputEventTail = null;  
  8.         }  
  9.         q.mNext = null;  
  10.   
  11.         mPendingInputEventCount -= 1;  
  12.         Trace.traceCounter(Trace.TRACE_TAG_INPUT, mPendingInputEventQueueLengthCounterName,  
  13.                 mPendingInputEventCount);  
  14.   
  15.         long eventTime = q.mEvent.getEventTimeNano();  
  16.         long oldestEventTime = eventTime;  
  17.         if (q.mEvent instanceof MotionEvent) {  
  18.             MotionEvent me = (MotionEvent)q.mEvent;  
  19.             if (me.getHistorySize() > 0) {  
  20.                 oldestEventTime = me.getHistoricalEventTimeNano(0);  
  21.             }  
  22.         }  
  23.         mChoreographer.mFrameInfo.updateInputEventTime(eventTime, oldestEventTime);  
  24.   
  25.         deliverInputEvent(q);  
  26.     }  
  27.   
  28.     // We are done processing all input events that we can process right now  
  29.     // so we can clear the pending flag immediately.  
  30.     if (mProcessInputEventsScheduled) {  
  31.         mProcessInputEventsScheduled = false;  
  32.         mHandler.removeMessages(MSG_PROCESS_INPUT_EVENTS);  
  33.     }  
  34. }  

z之后调用了deliverInputEvent(q)

ViewRootImpl.java

  1. private void deliverInputEvent(QueuedInputEvent q) {  
  2.     Trace.asyncTraceBegin(Trace.TRACE_TAG_VIEW, "deliverInputEvent",  
  3.             q.mEvent.getSequenceNumber());  
  4.     if (mInputEventConsistencyVerifier != null) {  
  5.         mInputEventConsistencyVerifier.onInputEvent(q.mEvent, 0);  
  6.     }  
  7.   
  8.     InputStage stage;  
  9.     if (q.shouldSendToSynthesizer()) {  
  10.         stage = mSyntheticInputStage;  
  11.     } else {  
  12.         stage = q.shouldSkipIme() ? mFirstPostImeInputStage : mFirstInputStage;  
  13.     }  
  14.   
  15.     if (stage != null) {  
  16.         stage.deliver(q);  
  17.     } else {  
  18.         finishInputEvent(q);  
  19.     }  
  20. }  

在这里初始化了一个InputStage类的实例,然后调用了该类的deliver(q),具体方法如下:

  1. /** 
  2.      * Base class for implementing a stage in the chain of responsibility 
  3.      * for processing input events. 
  4.      * <p> 
  5.      * Events are delivered to the stage by the {@link #deliver} method.  The stage 
  6.      * then has the choice of finishing the event or forwarding it to the next stage. 
  7.      * </p> 
  8.      */  
  9.     abstract class InputStage {  
  10.         private final InputStage mNext;  
  11.   
  12.         protected static final int FORWARD = 0;  
  13.         protected static final int FINISH_HANDLED = 1;  
  14.         protected static final int FINISH_NOT_HANDLED = 2;  
  15.   
  16.         /** 
  17.          * Creates an input stage. 
  18.          * @param next The next stage to which events should be forwarded. 
  19.          */  
  20.         public InputStage(InputStage next) {  
  21.             mNext = next;  
  22.         }  
  23.   
  24.         /** 
  25.          * Delivers an event to be processed. 
  26.          */  
  27.         public final void deliver(QueuedInputEvent q) {  
  28.             if ((q.mFlags & QueuedInputEvent.FLAG_FINISHED) != 0) {  
  29.                 forward(q);  
  30.             } else if (shouldDropInputEvent(q)) {  
  31.                 finish(q, false);  
  32.             } else {  
  33.                 apply(q, onProcess(q));  
  34.             }  
  35.         }  
  36.   
  37.         /** 
  38.          * Marks the the input event as finished then forwards it to the next stage. 
  39.          */  
  40.         protected void finish(QueuedInputEvent q, boolean handled) {  
  41.             q.mFlags |= QueuedInputEvent.FLAG_FINISHED;  
  42.             if (handled) {  
  43.                 q.mFlags |= QueuedInputEvent.FLAG_FINISHED_HANDLED;  
  44.             }  
  45.             forward(q);  
  46.         }  
  47.   
  48.         /** 
  49.          * Forwards the event to the next stage. 
  50.          */  
  51.         protected void forward(QueuedInputEvent q) {  
  52.             onDeliverToNext(q);  
  53.         }  
  54.   
  55.         /** 
  56.          * Applies a result code from {@link #onProcess} to the specified event. 
  57.          */  
  58.         protected void apply(QueuedInputEvent q, int result) {  
  59.             if (result == FORWARD) {  
  60.                 forward(q);  
  61.             } else if (result == FINISH_HANDLED) {  
  62.                 finish(q, true);  
  63.             } else if (result == FINISH_NOT_HANDLED) {  
  64.                 finish(q, false);  
  65.             } else {  
  66.                 throw new IllegalArgumentException("Invalid result: " + result);  
  67.             }  
  68.         }  
  69.   
  70.         /** 
  71.          * Called when an event is ready to be processed. 
  72.          * @return A result code indicating how the event was handled. 
  73.          */  
  74.         protected int onProcess(QueuedInputEvent q) {  
  75.             return FORWARD;  
  76.         }  
  77.   
  78.         /** 
  79.          * Called when an event is being delivered to the next stage. 
  80.          */  
  81.         protected void onDeliverToNext(QueuedInputEvent q) {  
  82.             if (DEBUG_INPUT_STAGES) {  
  83.                 Log.v(TAG, "Done with " + getClass().getSimpleName() + ". " + q);  
  84.             }  
  85.             if (mNext != null) {  
  86.                 mNext.deliver(q);  
  87.             } else {  
  88.                 finishInputEvent(q);  
  89.             }  
  90.         }  
  91.   
  92.         protected boolean shouldDropInputEvent(QueuedInputEvent q) {  
  93.             if (mView == null || !mAdded) {  
  94.                 Slog.w(TAG, "Dropping event due to root view being removed: " + q.mEvent);  
  95.                 return true;  
  96.             } else if ((!mAttachInfo.mHasWindowFocus  
  97.                     && !q.mEvent.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) || mStopped  
  98.                     || (mPausedForTransition && !isBack(q.mEvent))) {  
  99.                 // This is a focus event and the window doesn't currently have input focus or  
  100.                 // has stopped. This could be an event that came back from the previous stage  
  101.                 // but the window has lost focus or stopped in the meantime.  
  102.                 if (isTerminalInputEvent(q.mEvent)) {  
  103.                     // Don't drop terminal input events, however mark them as canceled.  
  104.                     q.mEvent.cancel();  
  105.                     Slog.w(TAG, "Cancelling event due to no window focus: " + q.mEvent);  
  106.                     return false;  
  107.                 }  
  108.   
  109.                 // Drop non-terminal input events.  
  110.                 Slog.w(TAG, "Dropping event due to no window focus: " + q.mEvent);  
  111.                 return true;  
  112.             }  
  113.             return false;  
  114.         }  
  115.   
  116.         void dump(String prefix, PrintWriter writer) {  
  117.             if (mNext != null) {  
  118.                 mNext.dump(prefix, writer);  
  119.             }  
  120.         }  
  121.   
  122.         private boolean isBack(InputEvent event) {  
  123.             if (event instanceof KeyEvent) {  
  124.                 return ((KeyEvent) event).getKeyCode() == KeyEvent.KEYCODE_BACK;  
  125.             } else {  
  126.                 return false;  
  127.             }  
  128.         }  
  129.     }  

对应方法栈可以看出,进过一些列调用最终会调用到ViewPostImeInputStage类的processPointerEvent方法.

ViewRootImpl.java

  1. private int processPointerEvent(QueuedInputEvent q) {  
  2.     final MotionEvent event = (MotionEvent)q.mEvent;  
  3.   
  4.     mAttachInfo.mUnbufferedDispatchRequested = false;  
  5.     boolean handled = mView.dispatchPointerEvent(event);  
  6.     if (mAttachInfo.mUnbufferedDispatchRequested && !mUnbufferedInputDispatch) {  
  7.         mUnbufferedInputDispatch = true;  
  8.         if (mConsumeBatchedInputScheduled) {  
  9.             scheduleConsumeBatchedInputImmediately();  
  10.         }  
  11.     }  
  12.     return handled ? FINISH_HANDLED : FORWARD;  
  13. }  

在该方法中调用了mView的dispatchPointerEvent,这个mView的初始化可以查看Activity的创建代码,在Activity创建的时候会给Activity设置一个根布局也就是DecorView,这里的mView就是DecorView,这个DecorView是PhoneWindow的私有内部类,它继承于FrameLayout并实现了RootViewSurfaceTaker接口,但是该方法是View类的一个final方法,子类无法覆写,直接查看View中的相应代码即可。代码如下:

View.java

  1. /** 
  2.  * Dispatch a pointer event. 
  3.  * <p> 
  4.  * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 
  5.  * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns 
  6.  * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 
  7.  * and should not be expected to handle other pointing device features. 
  8.  * </p> 
  9.  * 
  10.  * @param event The motion event to be dispatched. 
  11.  * @return True if the event was handled by the view, false otherwise. 
  12.  * @hide 
  13.  */  
  14. public final boolean dispatchPointerEvent(MotionEvent event) {  
  15.     if (event.isTouchEvent()) {  
  16.         return dispatchTouchEvent(event);  
  17.     } else {  
  18.         return dispatchGenericMotionEvent(event);  
  19.     }  
  20. }  

继续查看DecorView类中的dispatchTouchEvent方法,代码如下:

PhoneWindow.java

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

这个getCallback也就是当前的Activity,当当前Activity没有destroy的时候即调用该Activity的dispatchTouchEvent,这里代码就回到了应用层了,框架层完成了很多操作,这些操作只有查看源码才知道,这里终于回到了我们编写代码的地方了。当然这之后还是会通过框架层将对应的Touch事件传给对应的ViewGroup和View。下面先看下Activity中dispatchTouchEvent的代码:

Activity.java

  1. /** 
  2.  * Called to process touch screen events.  You can override this to 
  3.  * intercept all touch screen events before they are dispatched to the 
  4.  * window.  Be sure to call this implementation for touch screen events 
  5.  * that should be handled normally. 
  6.  * 
  7.  * @param ev The touch screen event. 
  8.  * 
  9.  * @return boolean Return true if this event was consumed. 
  10.  */  
  11. public boolean dispatchTouchEvent(MotionEvent ev) {  
  12.     if (ev.getAction() == MotionEvent.ACTION_DOWN) {  
  13.         onUserInteraction();  
  14.     }  
  15.     if (getWindow().superDispatchTouchEvent(ev)) {//这个getWindow就是PhoneWindow,也就是通过PhoneWindow继续对touch事件进行分发。  
  16.         return true;  
  17.     }//当上面返回true,也就是View把事件消费了,那么就不再调用Activity的onTouchEvent函数了。  
  18.     return onTouchEvent(ev);  
  19. }  

果然这里又回到了框架层,这里getWindow就是PhoneWindow,继续查看PhoneWindow的代码:

PhoneWindow.java

  1. @Override  
  2. public boolean superDispatchTouchEvent(MotionEvent event) {  
  3.     return mDecor.superDispatchTouchEvent(event);  
  4. }  

这里把事件就传给了DecorView进行分发。

PhoneWindow.java->DecorView

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

前面说过DecorView继承于FrameLayout,这里super.dispatchTouchEvent就是调用了FrameLayout里面的dispatchTouchEvent,而FrameLayout类中并未重写dispatchTouchEvent,因而直接调用的是ViewGroup中的dispatchTouchEvent。继续查看代码:

ViewGroup.java

  1. /** 
  2.  * {@inheritDoc} 
  3.  */  
  4. @Override  
  5. public boolean dispatchTouchEvent(MotionEvent ev) {  
  6.     if (mInputEventConsistencyVerifier != null) {  
  7.         mInputEventConsistencyVerifier.onTouchEvent(ev, 1);  
  8.     }  
  9.   
  10.     // If the event targets the accessibility focused view and this is it, start  
  11.     // normal event dispatch. Maybe a descendant is what will handle the click.  
  12.     if (ev.isTargetAccessibilityFocus() && isAccessibilityFocusedViewOrHost()) {  
  13.         ev.setTargetAccessibilityFocus(false);  
  14.     }  
  15.   
  16.     boolean handled = false;  
  17.     if (onFilterTouchEventForSecurity(ev)) {  
  18.         final int action = ev.getAction();  
  19.         final int actionMasked = action & MotionEvent.ACTION_MASK;  
  20.   
  21.         // Handle an initial down.  
  22.         if (actionMasked == MotionEvent.ACTION_DOWN) {  
  23.             // Throw away all previous state when starting a new touch gesture.  
  24.             // The framework may have dropped the up or cancel event for the previous gesture  
  25.             // due to an app switch, ANR, or some other state change.  
  26.             cancelAndClearTouchTargets(ev);  
  27.             resetTouchState();  
  28.         }  
  29.   
  30.         // Check for interception.  
  31.         final boolean intercepted;  
  32.         if (actionMasked == MotionEvent.ACTION_DOWN  
  33.                 || mFirstTouchTarget != null) {  
  34.             final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;  
  35.             if (!disallowIntercept) {  
  36.                 intercepted = onInterceptTouchEvent(ev);  
  37.                 ev.setAction(action); // restore action in case it was changed  
  38.             } else {  
  39.                 intercepted = false;  
  40.             }  
  41.         } else {  
  42.             // There are no touch targets and this action is not an initial down  
  43.             // so this view group continues to intercept touches.  
  44.             intercepted = true;  
  45.         }  
  46.   
  47.         // If intercepted, start normal event dispatch. Also if there is already  
  48.         // a view that is handling the gesture, do normal event dispatch.  
  49.         if (intercepted || mFirstTouchTarget != null) {  
  50.             ev.setTargetAccessibilityFocus(false);  
  51.         }  
  52.   
  53.         // Check for cancelation.  
  54.         final boolean canceled = resetCancelNextUpFlag(this)  
  55.                 || actionMasked == MotionEvent.ACTION_CANCEL;  
  56.   
  57.         // Update list of touch targets for pointer down, if needed.  
  58.         final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;  
  59.         TouchTarget newTouchTarget = null;  
  60.         boolean alreadyDispatchedToNewTouchTarget = false;  
  61.         if (!canceled && !intercepted) {  
  62.   
  63.             // If the event is targeting accessiiblity focus we give it to the  
  64.             // view that has accessibility focus and if it does not handle it  
  65.             // we clear the flag and dispatch the event to all children as usual.  
  66.             // We are looking up the accessibility focused host to avoid keeping  
  67.             // state since these events are very rare.  
  68.             View childWithAccessibilityFocus = ev.isTargetAccessibilityFocus()  
  69.                     ? findChildWithAccessibilityFocus() : null;  
  70.   
  71.             if (actionMasked == MotionEvent.ACTION_DOWN  
  72.                     || (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)  
  73.                     || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {  
  74.                 final int actionIndex = ev.getActionIndex(); // always 0 for down  
  75.                 final int idBitsToAssign = split ? 1 << ev.getPointerId(actionIndex)  
  76.                         : TouchTarget.ALL_POINTER_IDS;  
  77.   
  78.                 // Clean up earlier touch targets for this pointer id in case they  
  79.                 // have become out of sync.  
  80.                 removePointersFromTouchTargets(idBitsToAssign);  
  81.   
  82.                 final int childrenCount = mChildrenCount;  
  83.                 if (newTouchTarget == null && childrenCount != 0) {  
  84.                     final float x = ev.getX(actionIndex);  
  85.                     final float y = ev.getY(actionIndex);  
  86.                     // Find a child that can receive the event.  
  87.                     // Scan children from front to back.  
  88.                     final ArrayList<View> preorderedList = buildOrderedChildList();  
  89.                     final boolean customOrder = preorderedList == null  
  90.                             && isChildrenDrawingOrderEnabled();  
  91.                     final View[] children = mChildren;  
  92.                     for (int i = childrenCount - 1; i >= 0; i--) {  
  93.                         final int childIndex = customOrder  
  94.                                 ? getChildDrawingOrder(childrenCount, i) : i;  
  95.                         final View child = (preorderedList == null)  
  96.                                 ? children[childIndex] : preorderedList.get(childIndex);  
  97.   
  98.                         // If there is a view that has accessibility focus we want it  
  99.                         // to get the event first and if not handled we will perform a  
  100.                         // normal dispatch. We may do a double iteration but this is  
  101.                         // safer given the timeframe.  
  102.                         if (childWithAccessibilityFocus != null) {  
  103.                             if (childWithAccessibilityFocus != child) {  
  104.                                 continue;  
  105.                             }  
  106.                             childWithAccessibilityFocus = null;  
  107.                             i = childrenCount - 1;  
  108.                         }  
  109.   
  110.                         if (!canViewReceivePointerEvents(child)  
  111.                                 || !isTransformedTouchPointInView(x, y, child, null)) {  
  112.                             ev.setTargetAccessibilityFocus(false);  
  113.                             continue;  
  114.                         }  
  115.   
  116.                         newTouchTarget = getTouchTarget(child);  
  117.                         if (newTouchTarget != null) {  
  118.                             // Child is already receiving touch within its bounds.  
  119.                             // Give it the new pointer in addition to the ones it is handling.  
  120.                             newTouchTarget.pointerIdBits |= idBitsToAssign;  
  121.                             break;  
  122.                         }  
  123.   
  124.                         resetCancelNextUpFlag(child);  
  125.                         if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {  
  126.                             // Child wants to receive touch within its bounds.  
  127.                             mLastTouchDownTime = ev.getDownTime();  
  128.                             if (preorderedList != null) {  
  129.                                 // childIndex points into presorted list, find original index  
  130.                                 for (int j = 0; j < childrenCount; j++) {  
  131.                                     if (children[childIndex] == mChildren[j]) {  
  132.                                         mLastTouchDownIndex = j;  
  133.                                         break;  
  134.                                     }  
  135.                                 }  
  136.                             } else {  
  137.                                 mLastTouchDownIndex = childIndex;  
  138.                             }  
  139.                             mLastTouchDownX = ev.getX();  
  140.                             mLastTouchDownY = ev.getY();  
  141.                             newTouchTarget = addTouchTarget(child, idBitsToAssign);  
  142.                             alreadyDispatchedToNewTouchTarget = true;  
  143.                             break;  
  144.                         }  
  145.   
  146.                         // The accessibility focus didn't handle the event, so clear  
  147.                         // the flag and do a normal dispatch to all children.  
  148.                         ev.setTargetAccessibilityFocus(false);  
  149.                     }  
  150.                     if (preorderedList != null) preorderedList.clear();  
  151.                 }  
  152.   
  153.                 if (newTouchTarget == null && mFirstTouchTarget != null) {  
  154.                     // Did not find a child to receive the event.  
  155.                     // Assign the pointer to the least recently added target.  
  156.                     newTouchTarget = mFirstTouchTarget;  
  157.                     while (newTouchTarget.next != null) {  
  158.                         newTouchTarget = newTouchTarget.next;  
  159.                     }  
  160.                     newTouchTarget.pointerIdBits |= idBitsToAssign;  
  161.                 }  
  162.             }  
  163.         }  
  164.   
  165.         // Dispatch to touch targets.  
  166.         if (mFirstTouchTarget == null) {  
  167.             // No touch targets so treat this as an ordinary view.  
  168.             handled = dispatchTransformedTouchEvent(ev, canceled, null,  
  169.                     TouchTarget.ALL_POINTER_IDS);  
  170.         } else {  
  171.             // Dispatch to touch targets, excluding the new touch target if we already  
  172.             // dispatched to it.  Cancel touch targets if necessary.  
  173.             TouchTarget predecessor = null;  
  174.             TouchTarget target = mFirstTouchTarget;  
  175.             while (target != null) {  
  176.                 final TouchTarget next = target.next;  
  177.                 if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {  
  178.                     handled = true;  
  179.                 } else {  
  180.                     final boolean cancelChild = resetCancelNextUpFlag(target.child)  
  181.                             || intercepted;  
  182.                     if (dispatchTransformedTouchEvent(ev, cancelChild,  
  183.                             target.child, target.pointerIdBits)) {  
  184.                         handled = true;  
  185.                     }  
  186.                     if (cancelChild) {  
  187.                         if (predecessor == null) {  
  188.                             mFirstTouchTarget = next;  
  189.                         } else {  
  190.                             predecessor.next = next;  
  191.                         }  
  192.                         target.recycle();  
  193.                         target = next;  
  194.                         continue;  
  195.                     }  
  196.                 }  
  197.                 predecessor = target;  
  198.                 target = next;  
  199.             }  
  200.         }  
  201.   
  202.         // Update list of touch targets for pointer up or cancel, if needed.  
  203.         if (canceled  
  204.                 || actionMasked == MotionEvent.ACTION_UP  
  205.                 || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {  
  206.             resetTouchState();  
  207.         } else if (split && actionMasked == MotionEvent.ACTION_POINTER_UP) {  
  208.             final int actionIndex = ev.getActionIndex();  
  209.             final int idBitsToRemove = 1 << ev.getPointerId(actionIndex);  
  210.             removePointersFromTouchTargets(idBitsToRemove);  
  211.         }  
  212.     }  
  213.   
  214.     if (!handled && mInputEventConsistencyVerifier != null) {  
  215.         mInputEventConsistencyVerifier.onUnhandledEvent(ev, 1);  
  216.     }  
  217.     return handled;  
  218. }  

代码有点多,通过调试可知将会调用dispatchTransformedTouchEvent,查看代码如下:

ViewGroup.java

  1. /** 
  2.  * Transforms a motion event into the coordinate space of a particular child view, 
  3.  * filters out irrelevant pointer ids, and overrides its action if necessary. 
  4.  * If child is null, assumes the MotionEvent will be sent to this ViewGroup instead. 
  5.  */  
  6. private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,  
  7.         View child, int desiredPointerIdBits) {  
  8.     final boolean handled;  
  9.   
  10.     // Canceling motions is a special case.  We don't need to perform any transformations  
  11.     // or filtering.  The important part is the action, not the contents.  
  12.     final int oldAction = event.getAction();  
  13.     if (cancel || oldAction == MotionEvent.ACTION_CANCEL) {  
  14.         event.setAction(MotionEvent.ACTION_CANCEL);  
  15.         if (child == null) {  
  16.             handled = super.dispatchTouchEvent(event);  
  17.         } else {  
  18.             handled = child.dispatchTouchEvent(event);  
  19.         }  
  20.         event.setAction(oldAction);  
  21.         return handled;  
  22.     }  
  23.   
  24.     // Calculate the number of pointers to deliver.  
  25.     final int oldPointerIdBits = event.getPointerIdBits();  
  26.     final int newPointerIdBits = oldPointerIdBits & desiredPointerIdBits;  
  27.   
  28.     // If for some reason we ended up in an inconsistent state where it looks like we  
  29.     // might produce a motion event with no pointers in it, then drop the event.  
  30.     if (newPointerIdBits == 0) {  
  31.         return false;  
  32.     }  
  33.   
  34.     // If the number of pointers is the same and we don't need to perform any fancy  
  35.     // irreversible transformations, then we can reuse the motion event for this  
  36.     // dispatch as long as we are careful to revert any changes we make.  
  37.     // Otherwise we need to make a copy.  
  38.     final MotionEvent transformedEvent;  
  39.     if (newPointerIdBits == oldPointerIdBits) {  
  40.         if (child == null || child.hasIdentityMatrix()) {  
  41.             if (child == null) {  
  42.                 handled = super.dispatchTouchEvent(event);  
  43.             } else {  
  44.                 final float offsetX = mScrollX - child.mLeft;  
  45.                 final float offsetY = mScrollY - child.mTop;  
  46.                 event.offsetLocation(offsetX, offsetY);  
  47.   
  48.                 handled = child.dispatchTouchEvent(event);  
  49.   
  50.                 event.offsetLocation(-offsetX, -offsetY);  
  51.             }  
  52.             return handled;  
  53.         }  
  54.         transformedEvent = MotionEvent.obtain(event);  
  55.     } else {  
  56.         transformedEvent = event.split(newPointerIdBits);  
  57.     }  
  58.   
  59.     // Perform any necessary transformations and dispatch.  
  60.     if (child == null) {  
  61.         handled = super.dispatchTouchEvent(transformedEvent);  
  62.     } else {  
  63.         final float offsetX = mScrollX - child.mLeft;  
  64.         final float offsetY = mScrollY - child.mTop;  
  65.         transformedEvent.offsetLocation(offsetX, offsetY);  
  66.         if (! child.hasIdentityMatrix()) {  
  67.             transformedEvent.transform(child.getInverseMatrix());  
  68.         }  
  69.   
  70.         handled = child.dispatchTouchEvent(transformedEvent);  
  71.     }  
  72.   
  73.     // Done.  
  74.     transformedEvent.recycle();  
  75.     return handled;  
  76. }  

在该函数中调用了child.dispatchTouchEvent(),这里便走到了子View的dispatchTouchEvent中。子View也就是MyView,也就走到了TextView的dispathTouchEvent中,由于TextView并未重写dispathTouchEvent,因而直接进入View的dispatchTouchEvent中,代码如下:

View.java

  1. /** 
  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 the event should be handled by accessibility focus first.  
  10.     if (event.isTargetAccessibilityFocus()) {  
  11.         // We don't have focus or no virtual descendant has it, do not handle the event.  
  12.         if (!isAccessibilityFocusedViewOrHost()) {  
  13.             return false;  
  14.         }  
  15.         // We have focus and got the event, then use normal event dispatch.  
  16.         event.setTargetAccessibilityFocus(false);  
  17.     }  
  18.   
  19.     boolean result = false;  
  20.   
  21.     if (mInputEventConsistencyVerifier != null) {  
  22.         mInputEventConsistencyVerifier.onTouchEvent(event, 0);  
  23.     }  
  24.   
  25.     final int actionMasked = event.getActionMasked();  
  26.     if (actionMasked == MotionEvent.ACTION_DOWN) {  
  27.         // Defensive cleanup for new gesture  
  28.         stopNestedScroll();  
  29.     }  
  30.   
  31.     if (onFilterTouchEventForSecurity(event)) {  
  32.         //noinspection SimplifiableIfStatement  
  33.         ListenerInfo li = mListenerInfo;  
  34.         if (li != null && li.mOnTouchListener != null  
  35.                 && (mViewFlags & ENABLED_MASK) == ENABLED  
  36.                 && li.mOnTouchListener.onTouch(this, event)) {//在这里就调用了setOnTouchListener中的onTouch函数,如果有一个消费了,那么result=true  
  37.             result = true;  
  38.         }  
  39.   
  40.         if (!result && onTouchEvent(event)) {//当上面的result为true时,子View的onTouchEvent便不会执行了。  
  41.             result = true;  
  42.         }  
  43.     }  
  44.   
  45.     if (!result && mInputEventConsistencyVerifier != null) {  
  46.         mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);  
  47.     }  
  48.   
  49.     // Clean up after nested scrolls if this is the end of a gesture;  
  50.     // also cancel it if we tried an ACTION_DOWN but we didn't want the rest  
  51.     // of the gesture.  
  52.     if (actionMasked == MotionEvent.ACTION_UP ||  
  53.             actionMasked == MotionEvent.ACTION_CANCEL ||  
  54.             (actionMasked == MotionEvent.ACTION_DOWN && !result)) {  
  55.         stopNestedScroll();  
  56.     }  
  57.   
  58.     return result;  
  59. }  

在该函数中看到了在MainActivity中设置的setOnTouchListener对应的Listener接口,当setListener中的onTouch返回true时,MyView本身的onTouchEvent便不被调用。接下来看下View的onTouchEvent代码:

View.java

  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.   
  7.         if ((viewFlags & ENABLED_MASK) == DISABLED) {  
  8.             if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {  
  9.                 setPressed(false);  
  10.             }  
  11.             // A disabled view that is clickable still consumes the touch  
  12.             // events, it just doesn't respond to them.  
  13.             return (((viewFlags & CLICKABLE) == CLICKABLE  
  14.                     || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)  
  15.                     || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE);  
  16.         }  
  17.   
  18.         if (mTouchDelegate != null) {//一个View还可以设置TouchDelegate,也可以在TouchDelegate的onTouchEvent里面处理点击事件  
  19.             if (mTouchDelegate.onTouchEvent(event)) {  
  20.                 return true;  
  21.             }  
  22.         }  
  23.   
  24.         if (((viewFlags & CLICKABLE) == CLICKABLE ||  
  25.                 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) ||  
  26.                 (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) {  
  27.             switch (action) {  
  28.                 case MotionEvent.ACTION_UP:  
  29.                     boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;  
  30.                     if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {  
  31.                         // take focus if we don't have it already and we should in  
  32.                         // touch mode.  
  33.                         boolean focusTaken = false;  
  34.                         if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {  
  35.                             focusTaken = requestFocus();  
  36.                         }  
  37.   
  38.                         if (prepressed) {  
  39.                             // The button is being released before we actually  
  40.                             // showed it as pressed.  Make it show the pressed  
  41.                             // state now (before scheduling the click) to ensure  
  42.                             // the user sees it.  
  43.                             setPressed(true, x, y);  
  44.                        }  
  45.   
  46.                         if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {  
  47.                             // This is a tap, so remove the longpress check  
  48.                             removeLongPressCallback();  
  49.   
  50.                             // Only perform take click actions if we were in the pressed state  
  51.                             if (!focusTaken) {  
  52.                                 // Use a Runnable and post this rather than calling  
  53.                                 // performClick directly. This lets other visual state  
  54.                                 // of the view update before click actions start.  
  55.                                 if (mPerformClick == null) {  
  56.                                     mPerformClick = new PerformClick();  
  57.                                 }  
  58.                                 if (!post(mPerformClick)) {  
  59.                                     performClick();  
  60.                                 }  
  61.                             }  
  62.                         }  
  63.   
  64.                         if (mUnsetPressedState == null) {  
  65.                             mUnsetPressedState = new UnsetPressedState();  
  66.                         }  
  67.   
  68.                         if (prepressed) {  
  69.                             postDelayed(mUnsetPressedState,  
  70.                                     ViewConfiguration.getPressedStateDuration());  
  71.                         } else if (!post(mUnsetPressedState)) {  
  72.                             // If the post failed, unpress right now  
  73.                             mUnsetPressedState.run();  
  74.                         }  
  75.   
  76.                         removeTapCallback();  
  77.                     }  
  78.                     mIgnoreNextUpEvent = false;  
  79.                     break;  
  80.   
  81.                 case MotionEvent.ACTION_DOWN:  
  82.                     mHasPerformedLongPress = false;  
  83.   
  84.                     if (performButtonActionOnTouchDown(event)) {  
  85.                         break;  
  86.                     }  
  87.   
  88.                     // Walk up the hierarchy to determine if we're inside a scrolling container.  
  89.                     boolean isInScrollingContainer = isInScrollingContainer();  
  90.   
  91.                     // For views inside a scrolling container, delay the pressed feedback for  
  92.                     // a short period in case this is a scroll.  
  93.                     if (isInScrollingContainer) {  
  94.                         mPrivateFlags |= PFLAG_PREPRESSED;  
  95.                         if (mPendingCheckForTap == null) {  
  96.                             mPendingCheckForTap = new CheckForTap();  
  97.                         }  
  98.                         mPendingCheckForTap.x = event.getX();  
  99.                         mPendingCheckForTap.y = event.getY();  
  1. //这个注意下,这里会调用ViewRootImpl内部函数也就是后面的MOVE为啥知道前面DOWN了  

postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); } else { // Not inside a scrolling container, so show the feedback right away setPressed(true, x, y);

  1. //这个去检查是否有长按事件  

checkForLongClick(0); } break; case MotionEvent.ACTION_CANCEL: setPressed(false); removeTapCallback(); removeLongPressCallback(); mInContextButtonPress = false; mHasPerformedLongPress = false; mIgnoreNextUpEvent = false; break; case MotionEvent.ACTION_MOVE: drawableHotspotChanged(x, y); // 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; }这里仅分析下DOWN事件的处理,这里会先处理按钮自身的一些事件,具体事件见如下代码:

  1. /** 
  2.  * Performs button-related actions during a touch down event. 
  3.  * 
  4.  * @param event The event. 
  5.  * @return True if the down was consumed. 
  6.  * 
  7.  * @hide 
  8.  */  
  9. protected boolean performButtonActionOnTouchDown(MotionEvent event) {  
  10.     if (event.getToolType(0) == MotionEvent.TOOL_TYPE_MOUSE &&  
  11.         (event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {  
  12.         showContextMenu(event.getX(), event.getY(), event.getMetaState());  
  13.         mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;  
  14.         return true;  
  15.     }  
  16.     return false;  
  17. }  

然后判断当前View的父View是否在滚动,如果不在滚动就调用postDelayed:

View.java

  1. public boolean postDelayed(Runnable action, long delayMillis) {  
  2.     final AttachInfo attachInfo = mAttachInfo;  
  3.     if (attachInfo != null) {  
  4.         return attachInfo.mHandler.postDelayed(action, delayMillis);  
  5.     }  
  6.     // Assume that post will succeed later  
  7.     ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);  
  8.     return true;  
  9. }  

将action延迟一段时间,用于后续判断(是否长按事件,后续MOVE事件,UP事件)。

posted @ 2018-04-23 09:41  brave-sailor  阅读(1247)  评论(0编辑  收藏  举报