深入理解Android事件分发机制之源码分析

首先从Activity开始分发(一直看着这个ev,看看会往哪里传)

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

public abstract boolean superDispatchTouchEvent(MotionEvent event);
找到Window的实现类PhoneWindow

@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
    return mDecor.superDispatchTouchEvent(event);
}
所以Window会传给DecorView,它其实是Activity真正的根布局,继承自FrameLayout,里面包裹着你在xml中所设置的布局,所以他会向下分发。


ViewGroup核心代码

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); 
    } else {
        intercepted = false;
    }
} else {
    intercepted = true;
}
如果是down事件或者mFirstTouchTarget不为null。在后文,如果down事件被成功处理了,那么这个mFirstTouchTarget就会被赋值,那么当move,up事件来临的时候,这个条件就不会被满足,所以intercepted被置为true,代表了已拦截,这直接导致了onInterceptTouchEvent不会被调用,意思就是不会再启用拦截机制了,因为你已经决定消费它了。这验证了上文的猜测。


此外上文还提及了requestDisallowInceptTouchEvent方法。这是子View用来使得父ViewGroup的拦截机制无效化的东西!(除了down事件)

@Override
public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {

    if (disallowIntercept == ((mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0)) {
        return;
    }

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

   
    if (mParent != null) {
        mParent.requestDisallowInterceptTouchEvent(disallowIntercept);
    }
}
子View可以通过这个方法来给父类设置FLAG_DISALLOW_INTERCEPT这个标记位。可是为什么down事件不行?


// 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();
}

private void resetTouchState() {
    clearTouchTargets();
    resetCancelNextUpFlag(this);
    mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;
    mNestedScrollAxes = SCROLL_AXIS_NONE;
}

private void clearTouchTargets() {
    TouchTarget target = mFirstTouchTarget;
    if (target != null) {
        do {
            TouchTarget next = target.next;
            target.recycle();
            target = next;
        } while (target != null);
        mFirstTouchTarget = null;
    }
}

可以看到,如果是down事件的话,就会调用重置标记位的方法,这是解决滑动冲突的一个很重要的方法。不仅如此,mFirstTouchTarget也会被置为空,避免在下一次事件传来时干扰了他。


当ViewGroup的dispatchTouchEvent的返回值是super的时候,那么他将不会拦截事件,而是分发。所以可以看一下分发的代码。

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);

        // 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 (preorderedList != null) preorderedList.clear();
}
首先遍历,每个子元素需要满足2点条件才能接收到事件。

1.子元素是否在播放动画

2.点击事件的坐标是否落在子元素的区域内

这里的dispatchTransformedTouchEvent方法实际上就是就是调用了子元素的dispatchTouchEvent方法。所以我们看一下这个if语句。

假设子元素的dispatchTouchEvent返回的是true,那么会执行这个if里的这3行代码,并且break跳出循环。

newTouchTarget = addTouchTarget(child, idBitsToAssign);
alreadyDispatchedToNewTouchTarget = true;
break;

private TouchTarget addTouchTarget(@NonNull View child, int pointerIdBits) {
    final TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
    target.next = mFirstTouchTarget;
    mFirstTouchTarget = target;
    return target;
}

在这个addTouchTarget方法里,就完成了对mFirstTouchTarget的赋值(这个值就不为空了,验证了我们上面的猜测,move和up不会进入上面的那个if)。

假设子元素的dispatchTouchEvent返回的是false,ViewGroup就会继续遍历下一个子元素。


再细化一下dispatchTransformedTouchEvent方法,上面说了他调用了子元素的dispatchTouchEvent方法

if (cancel || oldAction == MotionEvent.ACTION_CANCEL) {
    event.setAction(MotionEvent.ACTION_CANCEL);
    if (child == null) {
        handled = super.dispatchTouchEvent(event);
    } else {
        handled = child.dispatchTouchEvent(event);
    }
    event.setAction(oldAction);
    return handled;
}
事件分发我们知道是一层层深入的。如果child非空,就会继续调用孩子的dispatchTouchEvent,以实现这个循环递归遍历的过程。从上面的分析到这里,算是一轮事件分发。


但是遍历完了,却找不到合适的子元素,有两种情况:

1.ViewGroup中没有子元素

2.子元素的dispatchTouchEvent返回了false或onTouchEvent中返回了false

这种情况下,ViewGroup会自己处理点击事件。


接着遍历子元素下面的代码看

// 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);
}
dispatchTransformedTouchEvent这个方法似曾相识,就是上面出现过的,调用孩子的dispatchTouchEvent的那个方法。但是注意,这一次第三个参数是null,本来是应该放孩子的。所以从前面这个方法内的if、else语句来看,如果它的孩子是空值,那么就意味着你传进来的这个child已经是view级别了,再也不是容器了,所以这个时候就要调用View的dispatchTouchEvent方法来着手处理事件了。


view的处理

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;
    }
}
这一段就是View对点击事件的处理过程了。首先会判断有没有onTouchListener,根据li.mOnTouchListener != null。其次li.mOnTouchListener.onTouch(this, event)代表假如onTouch方法返回的是true,那么onTouchEvent便不会被调用。这验证了我们onTouch更优先的结论。


进入onTouchEvent

if ((viewFlags & ENABLED_MASK) == DISABLED) {
    if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
        setPressed(false);
    }
    // A disabled view that is clickable still consumes the touch
    // events, it just doesn't respond to them.
    return (((viewFlags & CLICKABLE) == CLICKABLE
            || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
            || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE);
}
这里又印证了一个结论。(viewFlags & ENABLED_MASK) == DISABLED即使一个View是disable的,他依然会消费事件。


先看看up事件

if (((viewFlags & CLICKABLE) == CLICKABLE ||
        (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) ||
        (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) {
    switch (action) {
        case MotionEvent.ACTION_UP:
            boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
            if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
                ...

                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();
                        }
                    }
                }
if (((viewFlags & CLICKABLE) == CLICKABLE ||
        (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) ||
        (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) {

代表只要能长按,点击,甚至可点击状态,都可以消费事件。


然后关注这个方法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);
    return result;
}
当up事件发生,就会触发这个方法。如果这个View设置了onClickListener,li.mOnClickListener != null这句话,那么就会调用onClick方法。


setOnClickListener会 自动把View的CLICKABLE设为true,LONGCLICKABLE也是一样,所以不要好奇为什么设置的不可点击,结果还是能点击

public void setOnClickListener(@Nullable OnClickListener l) {
    if (!isClickable()) {
        setClickable(true);
    }
    getListenerInfo().mOnClickListener = l;
}
所以你想让点击事件失效,必须setclickable(false)在注册点击事件之后才行。而设置为enable为false就不会有这个情况了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值