Android笔记 触摸事件分发过程

2018-04-11  本文已影响0人  blossom_6694

1、触摸事件触发后,先会传到Activity的dispatchTouchEvent

public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            onUserInteraction();
        }
        //如果Window的superDispatchTouchEvent返回true,说明事件被消费  
        //如果返回false,则由Activity自身消费,即调用其onTouchEvent方法
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

2、getWindow()返回的是PhoneWindow对象,在PhoneWindow中又对调用Decorview的superDispatchTouchEvent, Decorview继承FrameLayout,FrameLayout继承自ViewGroup。
总结:getWindow().superDispatchTouchEvent(),作用是将触屏事件继续传递到ViewGroup层中。

final void attach(Context context, ActivityThread aThread,
            Instrumentation instr, IBinder token, int ident,
            Application application, Intent intent, ActivityInfo info,
            CharSequence title, Activity parent, String id,
            NonConfigurationInstances lastNonConfigurationInstances,
            Configuration config) {
        ...
        mWindow = PolicyManager.makeNewWindow(this);
}

//PolicyManager.java
public static Window makeNewWindow(Context context) {
    return sPolicy.makeNewWindow(context);
} 
//Policy
public Window makeNewWindow(Context context) {
    return new PhoneWindow(context);
} 

//PhoneWindow.java
public boolean superDispatchTouchEvent(MotionEvent event) {
    return mDecor.superDispatchTouchEvent(event);
}

//Decorview.java
public boolean superDispatchTouchEvent(MotionEvent event) {
    return super.dispatchTouchEvent(event);
}

3、在ViewGroup中会调用onInterceptTouchEvent方法,它是拦截触摸事件的接口。这个方法只有在ViewGroup中才有,如果ViewGroup不想将触摸事件传递给它的子View,则可以在onInterceptTouchEvent中进行拦截。返回值:true,表示ViewGroup拦截了该触摸事件;那么,该事件就不会分发给它的子View。否则,表示ViewGroup没有拦截该事件,该事件就会分发给它的子View。
4、如果ViewGroup不拦截该触摸事件,则会将该触摸事件递归分发给ViewGroup的子View。如果子View是ViewGroup类型,则会把事件递归到孩子的孩子。

上一篇 下一篇

猜你喜欢

热点阅读