Android事件分发机制详解(二)

在上一篇文章Android事件分发机制详解(一)中,介绍了View的事件分发,这篇文章主要介绍ViewGroup的事件分发机制以及点击和触摸事件是怎么传递的。

ViewGroup事件分发

在上一篇文章中,我们分析过在点击或者触摸View后,事件首先是传到ViewdispatchTouchEvent方法中处理,在ViewGroup也是同样的,首先也传到ViewGroup中的dispatchTouchEvent方法中处理,因为ViewGroup是继承View的。ViewGroup的事件分发与View的事件分发有点不同,ViewGroup事件分发过程中多了一个方法onInterceptTouchEvent,这个方法是用来拦截事件的,具体是怎么拦截的,我们来分析。

先来看看ViewGroup::dispatchTouchEvent的源码,源码很长,只贴关键片段:

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
...
boolean handled = false;
...
// Check for interception.
final boolean intercepted;
if (actionMasked == MotionEvent.ACTION_DOWN
    || mFirstTouchTarget != null) {
    final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
    if (!disallowIntercept) {
        intercepted = onInterceptTouchEvent(ev);
        ev.setAction(action); // restore action in case it was changed
    } else {
        intercepted = false;
    }
} else {
    // There are no touch targets and this action is not an initial down
    // so this view group continues to intercept touches.
    intercepted = true;
}
...
// Check for cancelation.
final boolean canceled = resetCancelNextUpFlag(this)
        || actionMasked == MotionEvent.ACTION_CANCEL;
if (!canceled && !intercepted) {
...
}
// Dispatch to touch targets.
if (mFirstTouchTarget == null) {
    // No touch targets so treat this as an ordinary view.
    handled = dispatchTransformedTouchEvent(ev, canceled, null,
        TouchTarget.ALL_POINTER_IDS);
}
...
return handled;
}

我们先来看ViewGroup是怎么拦截事件的,从上面的源码中第一个条件语句,可以看出来,在actionMasked == MotionEvent.ACTION_DOWN || mFirstTouchTarget != null时,才会出现intercpted = false的情况,而mFirstTouchTarget是在if (!canceled && !intercepted)条件语句中赋值的,这里没有贴出来,说明一下,是在addTouchTarget方法中赋值的,有兴趣的童鞋去读下源码就知道了。所以当intercpted为true时,mFirstTouchTarget总会为null,所以这里可以得出一个结论,onInterceptTouchEvent方法只有在MotionEvent.ACTION_DOWN时才会触发。
回到主题,当onInterceptTouchEvent方法返回true时,intercepted = true,那么mFirstTouchTarget == null成立,然后就会执行dispatchTransformedTouchEvent方法:

private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
            View child, int desiredPointerIdBits) {
    final boolean handled;
    ...
    // Perform any necessary transformations and dispatch.
    if (child == null) {
        handled = super.dispatchTouchEvent(transformedEvent);
    } else {
        final float offsetX = mScrollX - child.mLeft;
        final float offsetY = mScrollY - child.mTop;
        transformedEvent.offsetLocation(offsetX, offsetY);
        if (! child.hasIdentityMatrix()) {
            transformedEvent.transform(child.getInverseMatrix());
        }

        handled = child.dispatchTouchEvent(transformedEvent);
    }

    // Done.
    transformedEvent.recycle();
    return handled;
}

mFirstTouchTarget == null成立,dispatchTransformedTouchEvent的参数childnull,所以直接调用super.dispatchTouchEvent(transformedEvent)super就是View,这就回到了上篇文章中的流程了,不懂的可以回去看看上篇文章。既然执行的是super.dispatchTouchEvent(transformedEvent),那么事件就不会传递给子控件了,也就是说拦截掉了事件,ViewGroup自己处理了。
我们再来看看当intercepted == false时的情况,众所周知,当事件没有被拦截,肯定会传递给子控件的dispatchTouchEvent处理,到底是怎么传递的,请看下面if (!canceled && !intercepted)条件代码片段:

for (int i = childrenCount - 1; i >= 0; i--) {
    final int childIndex = getAndVerifyPreorderedIndex(
        childrenCount, i, customOrder);
    final View child = getAndVerifyPreorderedView(
        preorderedList, children, childIndex);

    // If there is a view that has accessibility focus we want it
    // to get the event first and if not handled we will perform a
    // normal dispatch. We may do a double iteration but this is
    // safer given the timeframe.
    if (childWithAccessibilityFocus != null) {
        if (childWithAccessibilityFocus != child) {
            continue;
        }
        childWithAccessibilityFocus = null;
        i = childrenCount - 1;
    }

    if (!canViewReceivePointerEvents(child)
        || !isTransformedTouchPointInView(x, y, child, null)) {
        ev.setTargetAccessibilityFocus(false);
        continue;
    }

    newTouchTarget = getTouchTarget(child);
    if (newTouchTarget != null) {
        // Child is already receiving touch within its bounds.
        // Give it the new pointer in addition to the ones it is handling.
        newTouchTarget.pointerIdBits |= idBitsToAssign;
        break;
    }

    resetCancelNextUpFlag(child);
    if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
        // Child wants to receive touch within its bounds.
        mLastTouchDownTime = ev.getDownTime();
        if (preorderedList != null) {
            // childIndex points into presorted list, find original index
            for (int j = 0; j < childrenCount; j++) {
                if (children[childIndex] == mChildren[j]) {
                    mLastTouchDownIndex = j;
                    break;
                }
            }
        } else {
            mLastTouchDownIndex = childIndex;
        }
        mLastTouchDownX = ev.getX();
        mLastTouchDownY = ev.getY();
        newTouchTarget = addTouchTarget(child, idBitsToAssign);
        alreadyDispatchedToNewTouchTarget = true;
        break;
    }

    // The accessibility focus didn't handle the event, so clear
    // the flag and do a normal dispatch to all children.
    ev.setTargetAccessibilityFocus(false);
}

这里是遍历子控件,当执行到if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign))时,child不为空,再看dispatchTransformedTouchEvent方法,会执行child.dispatchTouchEvent方法,如果child.dispatchTouchEvent返回false,还是不会执行addTouchTarget方法,也就是说mFirstTouchTarget还是为空,后续的事件,如ACTION_UP,ACTION_MOVE都默认被拦截了,不会再传给child,这就是上一篇文章预留问题的答案,dispatchTouchEvent的返回值的作用,这里也特别说明一下,ViewGroup继承View,所以ViewGroup::dispatchTouchEvent的返回值也是一样的,因为ViewGroup也可以为子控件。顺便提一下,onTouchEvent的返回值与dispatchTouchEvent的返回值作用是相同的,上一篇的代码仔细看过就会明白,就在View::dispatchTouchEvent方法中调用onTouchEvent的地方。
结合上一篇文章,得出简单流程图如下:

Android事件分发机制详解(二)_第1张图片

Activity事件传递内幕

经过前面的分析,已经了解了View以及ViewGroup的事件分发机制,那么问题来了,当我们点击一个按钮时,事件是怎么传到按钮的?
下面我们来继续从源码分析分析,相信大家都知道一个Activity对应一个Window,我们点击按钮时最先触发的是顶层ViewDecorViewdispatchTouchEvent方法,至于点击屏幕后事件怎么传递给DecorView的,这里涉及到WindowManagerServiceViewRootImpl创建窗口,有点复杂,暂时不分析。
先来看看DecorView::dispatchTouchEvent方法:

public boolean dispatchTouchEvent(MotionEvent ev) {
    final Window.Callback cb = mWindow.getCallback();
    return cb != null && !mWindow.isDestroyed() && mFeatureId < 0
                ? cb.dispatchTouchEvent(ev) : super.dispatchTouchEvent(ev);
}

该方法中mWindow.getCallback就是我们的Activity,因为在为Activity创建窗口时,会调用Activityattach方法,在attach方法中执行了mWindow.setCallback(this),所以这里返回的是Activity
也就是说在这里其实是调用Activity::dispatchTouchEvent方法。
我们来看看Activity::dispatchTouchEvent方法的实现(源码片段):

public boolean dispatchTouchEvent(MotionEvent ev) {
...
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
    onUserInteraction();
}
if (getWindow().superDispatchTouchEvent(ev)) {
    return true;
}
return onTouchEvent(ev);
}

onUserInteraction是个空方法,不用去分析,看第二个条件if (getWindow().superDispatchTouchEvent(ev))getWindow返回的是一个PhoneWindow,这里的条件相当于调用PhoneWindow::superDispatchTouchEvent(ev),它的源码是:

@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
    return mDecor.superDispatchTouchEvent(event);
}

很简单的一段代码,直接调用mDecorsuperDispatchTouchEvent方法。mDecor是在PhoneWindow构造方法里初始化的:

mDecor = (DecorView) preservedWindow.getDecorView();

也就是说mDecor是一个DecorView对象。再看DecorView::superDispatchTouchEvent方法:

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

DecorView继承于FrameLayout,而FrameLayout继承于ViewGroup,最终还是调用了ViewGroupdispatchTouchEvent方法,后面的流程就和我们前面分析的ViewGroup事件分发相同了,Over!

你可能感兴趣的:(Android,事件分发,android开发)