背景:研究Android的事件分发机制是如何实现的。
一、事件分发用到的方法:
1、public boolean dispatchTouchEvent(MotionEvent ev): 用于TouchEvent事件的分发;
2、public boolean onInterceptTouchEvent(MotionEvent ev):事件拦截;
3、boolean onTouch(View v, MotionEvent event): 事件的回调;
4、public boolean onTouchEvent(MotionEvent event): 用来处理事件
二、点击事件分发流程:先基于MotionEvent.ACTION_DOWN来研究
1、首先,当一个手机屏幕上的点击事件产生后,事件会先传递给当前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.
触摸屏幕事件的过程中被调用。可以通过复写该方法来拦截所有的触摸屏幕事件,在这些事件被传递给window之前。
为了这些被拦截的触摸屏幕事件能够被正常的处理,所以一定要调用该方法的实现方法。
*
* @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();//-----001 与用户交互
}
if (getWindow().superDispatchTouchEvent(ev)) {//------002
return true;
}
return onTouchEvent(ev);
}
(001)onUserInteraction() 处源码解读
/**
* Called whenever a key, touch, or trackball event is dispatched to the
* activity. Implement this method if you wish to know that the user has
* interacted with the device in some way while your activity is running.
* This callback and {@link #onUserLeaveHint} are intended to help
* activities manage status bar notifications intelligently; specifically,
* for helping activities determine the proper time to cancel a notfication.
当一个key、touch、或者trackball事件被分发给Activity,该方法则会被调用。可以实现该方法,如果你想知道
用户与设备间以某种方式交互,当该Activity正在运行。这个回调和onUserLeaveHint()方法旨在帮助Activities
智能的管理状态栏通知;帮助Activity在适当的时间取消通知。
*
* <p>All calls to your activity's {@link #onUserLeaveHint} callback will
* be accompanied by calls to {@link #onUserInteraction}. This
* ensures that your activity will be told of relevant user activity such
* as pulling down the notification pane and touching an item there.
所有Activity的onUserLeaveHint()回调方法的调用,都伴随着该方法的调用。这样做能够确保你的
Activity被告知相关的用户操作活动,例如拉下了通知栏面板并且点击一个item。
*
* <p>Note that this callback will be invoked for the touch down action
* that begins a touch gesture, but may not be invoked for the touch-moved
* and touch-up actions that follow.
注意,这个方法的回调只在触摸手势的Down操作,Move和Up操作不会被调用。
*
* @see #onUserLeaveHint()
*/
public void onUserInteraction() {
}
(002)getWindow().superDispatchTouchEvent(ev)源码解读:
1、getWindow():获取一个PhoneWindow的实现对象
/**
* Abstract base class for a top-level window look and behavior policy. An
* instance of this class should be used as the top-level view added to the
* window manager. It provides standard UI policies such as a background, title
* area, default key processing, etc.
*
* <p>The only existing implementation of this abstract class is
* android.view.PhoneWindow, which you should instantiate when needing a
* Window.
PhoneWindow是该抽象类的唯一实现类
*/
public abstract class Window {}
2、查看PhoneWindow.superDispatchTouchEvent(ev)方法实现:调用了DecorView的sup