Android事件分发机制之源码完美解析(下)

上篇文章解决了事件分发的核心问题,这篇文章就正式按顺序解决整个事件分发的源码了。

这篇文章很长,如果想快点看,推荐的阅读姿势是,自己看源码,哪里感觉比较晦涩,对照本文进行查找即可。


view group的dispatch


if (mInputEventConsistencyVerifier != null) {
    mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
}
一个检查器,检查嵌套的dispatch,比如view group中还有view group


// If the event targets the accessibility focused view and this is it, start
// normal event dispatch. Maybe a descendant is what will handle the click.
if (ev.isTargetAccessibilityFocus() && isAccessibilityFocusedViewOrHost()) {
    ev.setTargetAccessibilityFocus(false);
}
过滤掉不可访问、没有获得焦点的view


boolean handled = false;
if (onFilterTouchEventForSecurity(ev)) {
    final int action = ev.getAction();
    final int actionMasked = action & MotionEvent.ACTION_MASK;

    // Handle an initial down.
    if (actionMasked == MotionEvent.ACTION_DOWN) {
        // Throw away all previous state when starting a new touch gesture.
        // The framework may have dropped the up or cancel event for the previous gesture
        // due to an app switch, ANR, or some other state change.
        cancelAndClearTouchTargets(ev);
        resetTouchState();
    }
if判断,过滤掉那些被遮罩的view

下一个if,如果是down,就代表是新系列事件了,所以重置之前所有改变的东西。


// 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;
}
打断策略。上面的if,如果是down事件或者是mFirstTouchTarget不为空(之前找到了分发的child),就会进行打断的判断;反之,如果不是down事件,是move、up事件且mFirstTouchTarget为空(之前没有找到分发的child),直接就打断了,可以得出结论:如果child拒绝了down事件,后面的move、up事件,你也别想收到了!

再看上面的if里面的条件判断。有一个disallowIntercept的标记位。这个标记位是内部拦截法的核心。可以通过requestDisallowInterceptTouchEvent标记位允许或者是不允许父view group进行拦截。


看一看requestDisallowInterceptTouchEvent方法

@Override
public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {

    if (disallowIntercept == ((mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0)) {
        // We're already in this state, assume our ancestors are too
        return;
    }

    if (disallowIntercept) {
        mGroupFlags |= FLAG_DISALLOW_INTERCEPT;
    } else {
        mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;
    }

    // Pass it up to our parent
    if (mParent != null) {
        mParent.requestDisallowInterceptTouchEvent(disallowIntercept);
    }
}
最下面的if (mParent != null) 可以清除的看到,这是一个递归的形式。如果你在底层view调用的parent.requestDisallowInterceptTouchEvent。会不断调用父类的这个方法。所以所有的父容器的这个标记位,都是一样的。


继续回到view group的dispatch的源码

// If intercepted, start normal event dispatch. Also if there is already
// a view that is handling the gesture, do normal event dispatch.
if (intercepted || mFirstTouchTarget != null) {
    ev.setTargetAccessibilityFocus(false);
}
如果确定要打断或者之前有找到分发对象了,进行一个标记位的&(与)运算。因此isTargetAccessibilityFoucus() == false;而如果不打断且之前没找到分发对象,isTargetAccessibilityFoucus() ==true。这个标记位的主要目的是:找到你直接点击的且获得焦点的view,并且是属于当前这个view group的子view的。排除掉那些不属于这个view group的子view。


// Check for cancelation.
final boolean canceled = resetCancelNextUpFlag(this)
        || actionMasked == MotionEvent.ACTION_CANCEL;
判断是否是CANCEL状态。


// Update list of touch targets for pointer down, if needed.
final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;
TouchTarget newTouchTarget = null;
boolean alreadyDispatchedToNewTouchTarget = false;
if (!canceled && !intercepted) {

    // If the event is targeting accessiiblity focus we give it to the
    // view that has accessibility focus and if it does not handle it
    // we clear the flag and dispatch the event to all children as usual.
    // We are looking up the accessibility focused host to avoid keeping
    // state since these events are very rare.
    View childWithAccessibilityFocus = ev.isTargetAccessibilityFocus()
            ? findChildWithAccessibilityFocus() : null;
开始搜寻。看到最下面,isTargetAccessibilityFocus在这里起了作用。如果true,就找到你直接点击的且获得焦点的view,并且是属于当前这个view group的子view的。如果false,就是null。


if (actionMasked == MotionEvent.ACTION_DOWN
        || (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)
        || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
    final int actionIndex = ev.getActionIndex(); // always 0 for down
    final int idBitsToAssign = split ? 1 << ev.getPointerId(actionIndex)
            : TouchTarget.ALL_POINTER_IDS;

    // Clean up earlier touch targets for this pointer id in case they
    // have become out of sync.
    removePointersFromTouchTargets(idBitsToAssign);

    final int childrenCount = mChildrenCount;
    if (newTouchTarget == null && childrenCount != 0) {
        final float x = ev.getX(actionIndex);
        final float y = ev.getY(actionIndex);
        // Find a child that can receive the event.
        // Scan children from front to back.
        final ArrayList<View> preorderedList = buildTouchDispatchChildList();
        final boolean customOrder = preorderedList == null
                && isChildrenDrawingOrderEnabled();
        final View[] children = mChildren;
        for (int i = childrenCount - 1; i >= 0; i--) {
            final int childIndex = getAndVerifyPreorderedIndex(
                    childrenCount, i, customOrder);
            final View child = getAndVerifyPreorderedView(
                    preorderedList, children, childIndex);
进入for循环,开始搜寻自己的child,float的x,y就是后面用来判断是否落在子view区域内的东西


// 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;
}
上面获取的这个childWithAccessibilityFocus。注释的意思就是:这一系列的这个东西,其目的就是进行一个双重检查,为了更安全地给予时间片。

总结一下:其实childWithAccessibilityFocus其实就是内定人选了,一旦发现不是这个child,本次for循环就会continue,进入下个view的循环。其目的就是直接找到我们内定的这个view,如果不是他,直接舍弃。

childWithAccessibilityFocus = null;
    i = childrenCount - 1;
下面还有这两行代码。

所以整体的意思就是:childWithAccessibilityFocus是最有可能消费这个事件的view,我们第一个for循环,直接找到这个view,先行检查这个内定view的情况。如果它不符合,i重新设为childrenCount-1,重新进行无差别遍历搜寻。所以这个东西,是他们进行的一个算法型优化,小弟佩服之至。


if (!canViewReceivePointerEvents(child)
        || !isTransformedTouchPointInView(x, y, child, null)) {
    ev.setTargetAccessibilityFocus(false);
    continue;
}
如果落点不在这个子view内或者这个子view不能接受点击事件,直接过滤。


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;
}
过滤了这么多,靠谱的child可算是找到了。再从Touch Target历史链表中找,一看,如果有备份了,下面就不用进一步确认了;如果没有,就继续找,而这个继续找,多半是事件第一次的情况,即down事件,如果不是down事件而是move、up事件,那多半是CANCEL了。(TouchTarget这个链表机制多半是历史记录)


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;
}
dispatchTransformedTouchEvent如果返回true,就会执行下面的逻辑。这个方法在上篇文章中有过详细的讲解了。


if (newTouchTarget == null && mFirstTouchTarget != null) {
    // Did not find a child to receive the event.
    // Assign the pointer to the least recently added target.
    newTouchTarget = mFirstTouchTarget;
    while (newTouchTarget.next != null) {
        newTouchTarget = newTouchTarget.next;
    }
    newTouchTarget.pointerIdBits |= idBitsToAssign;
}
newTouchTarget == null代表这一轮,没有找到child分发对象。mFirstTouchTarget != null代表的是上一轮是有找到分发对象的。这多半就是CANCEL的情况了。在这里设置的标记位,下面都会用到。


// 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);
} else {
    // Dispatch to touch targets, excluding the new touch target if we already
    // dispatched to it.  Cancel touch targets if necessary.
    TouchTarget predecessor = null;
    TouchTarget target = mFirstTouchTarget;
    while (target != null) {
        final TouchTarget next = target.next;
        if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
            handled = true;
        } else {
            final boolean cancelChild = resetCancelNextUpFlag(target.child)
                    || intercepted;
            if (dispatchTransformedTouchEvent(ev, cancelChild,
                    target.child, target.pointerIdBits)) {
                handled = true;
            }
            if (cancelChild) {
                if (predecessor == null) {
                    mFirstTouchTarget = next;
                } else {
                    predecessor.next = next;
                }
                target.recycle();
                target = next;
                continue;
            }
        }
        predecessor = target;
        target = next;
    }
}
上面的if在上文也充分分析过了,代表着没有孩子接受,自己进行一个接受事件的情况。下面的else多半是CANCEL情况。


// Update list of touch targets for pointer up or cancel, if needed.
if (canceled
        || actionMasked == MotionEvent.ACTION_UP
        || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
    resetTouchState();
} else if (split && actionMasked == MotionEvent.ACTION_POINTER_UP) {
    final int actionIndex = ev.getActionIndex();
    final int idBitsToRemove = 1 << ev.getPointerId(actionIndex);
    removePointersFromTouchTargets(idBitsToRemove);
}
这里是结束的情况:包括CANCEL,UP等。


if (!handled && mInputEventConsistencyVerifier != null) {
    mInputEventConsistencyVerifier.onUnhandledEvent(ev, 1);
}
return handled;
只有以前检查过,才会检查这个方法。其主要目的是通知事件的痕迹应该被忽略,并进行一些列标记位的设置(多半是标识本次事件无人接收)。



view的dispatch


// If the event should be handled by accessibility focus first.
if (event.isTargetAccessibilityFocus()) {
    // We don't have focus or no virtual descendant has it, do not handle the event.
    if (!isAccessibilityFocusedViewOrHost()) {
        return false;
    }
    // We have focus and got the event, then use normal event dispatch.
    event.setTargetAccessibilityFocus(false);
}
event.setTargetAccessibilityFocus(false);就是听过这个标记位,告诉其他view,这个事件有主了,我消费了!


if (onFilterTouchEventForSecurity(event)) {
    if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
        result = true;
    }
    //noinspection SimplifiableIfStatement
    ListenerInfo li = mListenerInfo;
    if (li != null && li.mOnTouchListener != null
            && (mViewFlags & ENABLED_MASK) == ENABLED
            && li.mOnTouchListener.onTouch(this, event)) {
        result = true;
    }

    if (!result && onTouchEvent(event)) {
        result = true;
    }
}
1.如果view是enable,直接消费

2.如果view是enable,且onTouch返回true,直接消费

3.但是如果view是enable,且onTouch返回true,那onTouchEvent就得不到执行了。事件被onTouch消费了

4.如果view不是enable的,不管onTouch有没有,返回的是true还是false,onTouchEvent就会得到执行。

但是开了个Demo测试一下,是错的。

handleScrollBarDragging(event)多半是返回的false。

所以结论调整为:view 1.ENABLE 2.onTouch返回true的时候,onTouchEvent不会得到执行。


view的onTouchEvent


final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE
        || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
        || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
clickable、long_clickable、context_clickable3者之间有一个符合,那就是clickable。这个context_clickable是啥意思,看了看注释:如主触笔按下或鼠标右键单击。


if ((viewFlags & ENABLED_MASK) == DISABLED) {
    if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
        setPressed(false);
    }
    mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
    // A disabled view that is clickable still consumes the touch
    // events, it just doesn't respond to them.
    return clickable;
}
如果这个view是DISABLE的,那么就会进入这个逻辑,直接以是否clickable作为返回值。后来测试了下,又结合源码看了一下,即使是ENABLE的时候,也多半是以clickable作为返回值。这一点下面会有证明,自己也可以写一个demo测试一下。


if (mTouchDelegate != null) {
    if (mTouchDelegate.onTouchEvent(event)) {
        return true;
    }
}
touch delegate就是一个很神奇的东西了。即一个view group可以设置他的区域内任何一块区域,然后如果点击事件在这个区域内,他将会把这个点击事件赠送给某个view,这个view可以自己进行设定。详细可以看我的置顶文章:Android之View的TouchDelegate,你真的理解事件分发了吗???http://blog.csdn.net/qq_36523667/article/details/79175287


if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
    switch (action) {
        case MotionEvent.ACTION_UP:
            mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
            if ((viewFlags & TOOLTIP) == TOOLTIP) {
                handleTooltipUp();
            }
            if (!clickable) {
                removeTapCallback();
                removeLongPressCallback();
                mInContextButtonPress = false;
                mHasPerformedLongPress = false;
                mIgnoreNextUpEvent = false;
                break;
            }

这个TOOLTIP可能是是否设置提示框、提示信息啥的。如果是有TOOLTIP但是clickable为false的情况直接break了,并且onTouchEvent返回true。

所以下面的情况是又有TOOLTIP,clickable又是true的情况。


boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
判断是否未松开(即按下)的状态。如果是,就会进入if的逻辑。


boolean focusTaken = false;
if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
    focusTaken = requestFocus();
}
如果是可获取焦点的,就获取焦点


if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
    // This is a tap, so remove the longpress check
    removeLongPressCallback();

    // Only perform take click actions if we were in the pressed state
    if (!focusTaken) {
        // Use a Runnable and post this rather than calling
        // performClick directly. This lets other visual state
        // of the view update before click actions start.
        if (mPerformClick == null) {
            mPerformClick = new PerformClick();
        }
        if (!post(mPerformClick)) {
            performClick();
        }
    }
}
只有当我们处于按下状态的时候,我们才会执行performClick();即onClickListener的代码,逻辑很简单,先开子线程执行试试,如果失败,直接执行点击事件。


performClick

public boolean performClick() {
    final boolean result;
    final ListenerInfo li = mListenerInfo;
    if (li != null && li.mOnClickListener != null) {
        playSoundEffect(SoundEffectConstants.CLICK);
        li.mOnClickListener.onClick(this);
        result = true;
    } else {
        result = false;
    }

    sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);

    notifyEnterOrExitForAutoFillIfNeeded(true);

    return result;
}
void onClick(View v);
执行了回调。而且注意点击事件,在UP事件中才能生效


另外的几个事件,都不用再分析了。毫无用处。

得出结论:

1.如果撇开那个奇怪的TOOLTIP不谈,onTouchEvent的返回值,就看clickable

2.UP事件中,是点击事件的执行处。所以,一旦UP事件得不到执行,点击事件自然也就得不到执行。所以当你重写view的onTouchEvent的时候,且你没有返回super.onTouchEvent,而是true或者false,那么你的onClickListener算是报废了,可以开个demo自行测试一下。

3.如果你的view是clickable的,那么你返回super和返回true毫无区别,都是代表着消费。

4.结合2,3。所以你如果又想消费,又想不让onClickListener失效,推荐你返回super。


本文算是分析事件分发,网上最详尽的一篇了。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值