且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Android事件分发详解(二)——Touch事件传入到Activity的流程

更新时间:2021-09-09 00:52:56

PS:
该系列博客已更新,详情请参见:

http://blog.csdn.net/lfdfhl/article/details/50707742

http://blog.csdn.net/lfdfhl/article/details/50707731

http://blog.csdn.net/lfdfhl/article/details/50707724

http://blog.csdn.net/lfdfhl/article/details/50707721

http://blog.csdn.net/lfdfhl/article/details/50707714

http://blog.csdn.net/lfdfhl/article/details/50707713

http://blog.csdn.net/lfdfhl/article/details/50707700

* Demo描述:

 * Touch事件传入到Activity的流程
 * 
 * 设备上Touch事件首先是传递到了Activity,再由Activity传递到
 * 外层布局ViewGroup,再到内层ViewGroup,最后直到内层ViewGroup里的某个View.
 * 这就是事件的传递.
 * 
 * 在此看一下Touch事件传递到Activity,再由Activity传递到外层布局ViewGroup的过程.
 * 主要看的还是Touch事件由Activity传递到外层布局ViewGroup的过程
 * 1 Touch事件传递到Activity的过程.
 *   该过程有些复杂,能力有限,看不懂;亦不是应用开发的重点,故略过.
 * 2 Activity传递Touch事件到外层布局ViewGroup的过程
 *   首先会传递到Activity的dispatchTouchEvent()方法,源码如下:
 *   public boolean dispatchTouchEvent(MotionEvent ev) {
 *      if (ev.getAction() == MotionEvent.ACTION_DOWN) {
 *          onUserInteraction();
 *       }
 *      if (getWindow().superDispatchTouchEvent(ev)) {
 *         return true;
 *      }
 *      return onTouchEvent(ev);
 *   }
 *   
 *  (1)onUserInteraction()方法是空方法,暂且不管.
 *  (2)调用getWindow().superDispatchTouchEvent(ev)
 *     即调用了PhoneWindow的superDispatchTouchEvent(ev)方法.
 *     @Override
 *     public boolean superDispatchTouchEvent(MotionEvent event) {
 *        return mDecor.superDispatchTouchEvent(event);
 *     }
 *     在该方法中会调用DecorView的superDispatchTouchEvent(event)方法.
 *     DecorView是一个定义在PhoneWindow中的一个内部类.定义如下:
 *     private final class DecorView extends FrameLayout implements RootViewSurfaceTaker{}
 *     发现没有,它是继承自FrameLayout的?其实,系统会对任意一个Activity的最外层布局嵌套一个FrameLayout.
 *     嗯哼,是不是暗示着什么........
 *     继续看DecorView的superDispatchTouchEvent(event)方法,源码如下:
 *     public boolean superDispatchTouchEvent(MotionEvent event) {
 *        return super.dispatchTouchEvent(event);
 *     }
 *     在该方法中方法中调用了super.dispatchTouchEvent(event);
 *     即调用了FrameLayout(也就是ViewGroup)的dispatchTouchEvent(event);
 *     剩下的流程就和ViewGroup的事件分发一致了.
 * (3)如果getWindow().superDispatchTouchEvent(ev)方法返回的false即事件未被消费.
 *    此时if条件不满足,于是代码继续往下执行那么就会调用onTouchEvent(ev)
 *    也就是Activity的onTouchEvent(MotionEvent event).
 *    剩下的流程也不用多说了.
 * 
 * 参考资料:
 * http://feelyou.info/analyze_android_touch_event/
 * Thank you very much
 */