一般咱们处理事情,都是针对某一个View来处理了,要么是增加onTouchListener监听器,要么承继View然后重写View#onTouchEvent,
乃至不必重写,只需运用Widget自己的监听函数 ,或许GestureDetector就OK了.
可是了解Android事情模型,关于了解GestureDetector,及Android事情的交互,写出具有超卓的交互的使用.
都是必经之路.
一:ViewGroup与View的事情模型
咱们都知道Android界面实践是一棵View的树.枝干是ViewGroup.
ViewGroup承继自View,可是又是办理View的容器.那么ViewGroup与View的事情联系是怎样样的呢?
这需要从另一个重要的ViewGroup中的办法,如下说起:
1public boolean onInterceptTouchEvent(MotionEvent ev) {
2 return false;
3}
它的默许完成很简略,便是把事情交给子View去处理.自己不阻拦.
Intercept便是阻拦的意思.
此办法的注释,关于ViewGroup与View的事情模型说得很清楚,
首要是以下几点:
(1) 假如此办法回来false,阐明此ViewGroup暂时(仅仅暂时)关于触控事情不感兴趣.
可是不知道后边的事情它感不感兴趣.所以后续事情还会一向传递到此办法中来,供此办法判别.
(2) 假如此办法回来true了.那么阐明此办法对应的ViewGroup开端关于此事情(或许手势)感兴趣了.
那么后续事情就会直接给此办法对应的ViewGroup的onTouchEvent办法来处理事情了.
(3) 假如此办法一开端回来false,说不感兴趣这个时分事情发给了目录View.
现在又回来true,说感兴趣了.那么目录View就会收到一个action为ACTION_CANCEL的事情.
跟此办法回来true时的事情是同一个事情 ,仅仅action变了.
(4) ViewGroup会在这儿接纳触控开端的事情.
规矩便是上面这些 ,那么是谁在后边处理这些规矩呢?
便是ViewGroup.它在disptachTouchEvent办法中,进行了一系列的处理来完成这种模型.
public boolean dispatchTouchEvent(MotionEvent ev)
关于独自的View自身来说,它也有一个简略的事情派发模型.经过以下代码就可以很理解的看出来了:
View#dispatchTouchEvent(MotionEvent event):
1ListenerInfo li = mListenerInfo;
2if (li != null li.mOnTouchListener != null (mViewFlags ENABLED_MASK) == ENABLED
3 li.mOnTouchListener.onTouch(this, event)) {
4 return true;
5}
6
7if (onTouchEvent(event)) {
8 return true;
9}
二: Activity与View的事情模型
事情先到Activity中,然后Activity调用:
01/**
02 * Called to process touch screen events. You can override this to
03 * intercept all touch screen events before they are dispatched to the
04 * window. Be sure to call this implementation for touch screen events
05 * that should be handled normally.
06 *
07 * @param ev The touch screen event.
08 *
09 * @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)) {
16 return true;
17 }
18 return onTouchEvent(ev);
19 }
来分发事情, 这儿的逻辑是:
先让用户界面窗口处理:getWindow().superDispatchTouchEvent(ev)
假如窗口没有处理这个事情.
那就交给Activity自己处理.return onTouchEvent(ev)
这个Window跟View层级是怎样交互的呢?
咱们找到了Window的完成类:PhoneWindow(com.android.internal.policy.impl.PhoneWindow)
1@Override
2 public boolean superDispatchTouchEvent(MotionEvent event) {
3 return mDecor.superDispatchTouchEvent(event);
4 }
这个mDecor便是用户界面的根View了.
private final class DecorView extends FrameLayout
(com.android.internal.policy.impl.PhoneWindow.DecorView)
本来窗口将事情交给根View来进行事情派发的.
mDecor调用自己的superDispatchTouchEvent(event)
然后将事情派发的使命交给了自己的dispatchTouchEvent
1public boolean superDispatchTouchEvent(MotionEvent event) {
2 return super.dispatchTouchEvent(event);
3}
这儿调用的super.dispatchTouchEvent 便是ViewGroup的声明的dispatchTouchEvent的了.