Android触屏事件传递机制


转自: http://www.apkbus.com/android-52486-1-1.html

首先,需要了解:View中有两个方法:dispatchTouchEvent,onTouchEvent

                ViewGroup中有三个方法:dispatchTouchEvent,onTouchEvent,onInterceptTouchEvent
                Activitiy中有两个方法:dispatchTouchEvent,onTouchEvent
其中dispatchTouchEvent是用来分发Touch事件的
    onInterceptTouchEvent是用来处理是否截断Touch事件的
    onTouchEvent是用来处理接收到的Touch事件的。
并且在Activity中还有一个onUserInteraction会在Activity的dispatchTouchEvent后被调用


当View中的onTouchEvent返回值为true的时候,就会处理所有传过来的TouchEvent,并且到此结束,不会向下传递。
当View中的onTouchEvent返回值为false的时候,就只会处理DOWN事件,而不会处理MOVE,UP事件,并且将所有的TouchEvent向下传递。传递给ViewGroup和Activity,如果ViewGroup中的onTouchEvent返回为true时,就会处理所有的TouchEvent,若为false则只会处理DOWN事件,不会处理MOVE事件,并且将事件传递给Activity。

而onInterceptTouchEvent是用来表示是否截断触屏事件,当onInterceptTouchEvent返回值为true的时候,说明会截断,并且将此次的TouchEvent交给该ViewGroup中的onTouchEvent来处理,但是DOWN事件都不会传递下去,全部交给ViewGroup的onTouchEvent来处理,如果onTouchEvent中返回false的话,就会交给下一层的ViewGroup或者Activity的onTouchEvent来处理,如果返回true的话,就会在该层ViewGroup的onTouchEvent处理所有的TouchEvent。当onInterceptTouchEvent中返回为true的时候,除了DOWN事件会经过这层的onInterceptTouchEvent方法,而MOVE,UP则不会,它们会直接交给该层的onTouchEvent方法进行处理,而不会调用onInterceptTouchEvent方法。

dispatchTouchEvent负责分发TouchEvent,当dispatchTouchEvent中返回为false的时候就会返回,等待下一次TouchEvent的到来,而不将TouchEvent分发出去,而当返回为true的时候,就会询问onInterceptTouchEvent,是否拦截此TouchEvent。并且不会向下传递了。当Activity中的dispatchTouchEvent中返回false或者true的时候,就会只执行dispatchTouchEvent,不会将Touch事件向下传递,也不会给onTouchEvent进行处理。当ViewGroup中返回了false之后,则除了DOWN事件之外的其他事件也不会进入到该ViewGroup中,即接下来的MOVE,UP事件不会再经过此ViewGroup和下面的ViewGroup以及View了。而在此层的上一层进行TouchEvent的处理,如果那一层的onTouchEvent不能处理,则会给它的parentView中onTouchEvent进行处理。

总结:首先TouchEvent传递事件顺序是:Activity的dispatchTouchEvent,如果dispatchTouchEvent返回的是true或者false,则表示不会将事件分发出去,并且等待下一次TouchEvent的到来,再进行处理。当dispatchTouchEvent的返回值为super.dispatchTouchEvent的时候,则会将Activity所接受的TouchEvent传递给ViewGroup,当ViewGroup中的dispatchTouchEvent返回值为true的话,则表示等待下一次TouchEvent,并且不会将TouchEvent传递给子ViewGroup或者View,如果返回为false或者super.dispatchTouchEvent,则会询问该ViewGroup中的onInterceptTouchEvent,如果onInterceptTouchEvent返回为true的话,就说明截取了此次TouchEvent,给该层的onTouchEvent进行处理,如果返回为false的话,则说明不会截取此次的TouchEvent,并且继续向下传递,询问下一层ViewGroup的dispatchTouchEvent。继续循环,直到到了View的时候,如果onTouchEvent返回为true的时候,就会处理所有的TouchEvent包括DOWN,MOVE,UP,如果返回为false或者super.onTouchEvent的话,就只处理DOWN事件,而其它事件包括DOWN事件则会交给上一层的ViewGroup中的onTouchEvent进行处理。



其他参考博文:http://orgcent.com/android-touch-event-mechanism/ 
http://www.cnblogs.com/playing/archive/2011/06/16/2082564.html
http://www.360doc.com/content/11/0221/18/15055_94878114.shtml

你可能感兴趣的:(Android触屏事件传递机制)