View的事件传递原理和源码分析

本文将将接View的事件传递机制,通过本文的学习,将能够更好的自定义出我们想要的View。

一、点击事件的传递规则

在讲解源码之前,我们首先介绍一下我们比较熟知的三个方法。

public boolean dispatchTouchEvent(MotionEvent ev)

用于事件的分发,如果事件传递到此View,那么一定会调用此方法,返回结果受到onInterceptTouchEvent和onTouchEvent的返回值影响

public boolean onInterceptTouchEvent(MotionEvent ev)

用于事件的拦截,如果当前View拦截了某个事件,那么在同一个事件序列当中,此方法不会被再次调用,返回结果表示是否拦截当前事件。

public boolean onTouchEvent(MotionEvent event)

在dispatchTouchEvent方法中调用,用来处理点击事件,返回结果表示是否消耗当前事件爱你,如果不消耗,则在同一事件序列中,当前View无法再次收到事件。

关于事件传递机制,这里给出一些结论,根据这些结论可以更好的理解整个传递机制:(摘自《Android开发艺术探索》)

(1)同一个事件序列是从手指触摸屏幕的那一刻起,到手指离开屏幕的那一刻结束。在这个过程产生的一系列事件,这个事件序列以down事件开始,中间含有数量补丁的move事件,最终以up事件结束。

(2)正常情况下,一个事件序列只能被一个View拦截且消耗,因为一旦一个元素拦截了某个事件,那么同一事件序列中的其他事件将会直接交给它处理,因此同一事件序列中的事件不能分别由两个View同时处理,但是通过特殊手段可以做到,比如一个View将本该自己处理的事件通过onTouchEvent强行传递给其他View处理。

(3)某个View一旦决定拦截,那么这一个事件序列都只能由它来处理(如果事件序列能够传递给它的话),并且这个View的onInterceptTouchEvent不会再被调用。这条也好理解,就是说当一个View决定拦截一个事件后,那么系统会把同一事件序列内的其他方法都直接交给它来处理,因此不用再调用这个View的onInterceptTouchEvent去询问它是否要拦截了。

(4)某个View一旦开始处理事件,如果它不消耗ACTION_DOWN事件(onTouchEvent返回了false),那么同一事件序列中的其他事件都不会再交给它来处理,并且事件重新交由它的父元素去处理,及父元素的onTouchEvent将会被调用。意思是事件一旦交给一个View处理,那么它就必须消耗掉,否则同一事件序列中的其他事件不会再交给他处理

(5)如果View不消耗除ACTOION_DOWN以外的其他事件,那么这个点击事件将会消失,此时父元素的onTouchEvent并不会被调用,并且当前View可以持续受到后续的实践,最终这个消失的点击事件会传递给Activity处理。

(6)ViewGroup默认不拦截任何事件,Android源码中ViewGroup的onInterceptTouchEvent方法默认返回false。

(7)View没有onInterceptTouchEvent方法,一旦有点击事件传递给他,那么他的onTouchEvent方法就会被调用

(8)View的onTouchEvent默认会消耗事件(return true),除非它是不可点击的(clickable和longClickable同时为false),View的longClickable属性默认为false,clickable属性要分情况,比如Button的clickable属性默认为true,而TextView的clickable属性默认为false。

(9)View的enable属性不影响onTouchEvent的默认返回值,哪怕一个View是disable状态,只要它的clickable或者longClickable有一个为true,那么它的onTouchEvent就返回true

(10)onClick会发生的前提是当前View是可点击的,并且它收到了down和up的事件

(11)事件传递过程总是从外向内的,即事件总是先传递给父元素,然后再由父元素分发给View,通过requestDisallowInterceptTouchEvent方法可以在子元素中干预父元素的事件分发过程,但是ACTION_DOWN事件除外。

二、事件传递源码分析

1、activity对点击事件的分发过程

activity的源码起始是在dispatchTouchEvent开始,其源码如下:

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

从源码中我们可以看出,activity的dispatchTouchEvent会调用getWindow().superDispatchTouchEvent,其实是调用PhoneWindow的superDispatchTouchEvent,如果superDispatchTouchEvent返回false,也就是这个事件没有View去处理,那么就会调用Activity的onTouchEvent

我们再看PhoneWindow的superDispatchTouchEvent源码:

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

这个调用了DecorView的superDispatchTouchEvent,

DecorView源码:

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

继续调用了super.dispatchTouchEvent,DecorView是FrameLayout的子类,FrameLayout是ViewGroup的子类,最终调用了ViewGroup的dispatchTouchEvent方法

我们来看ViewGroup的dispatchTouchEvent,由于代码比较长,我们先只看一段::

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

这段主要是传递前做一些清理重置工作,重置一些比较重要的标记,比较重要的是置空mFirstTouchTarget(如果有子View处理事件则会被赋值)和清除FLAG_DISALLOW_INTERCEPT标记(通过requestDisallowInterceptTouchEvent设置的标记)

再继续往下看:

final boolean intercepted;

//如果是down事件或者mFirstTouchTarget不等于空

if (actionMasked == MotionEvent.ACTION_DOWN

|| mFirstTouchTarget != null) {

//并且当前View并没有设置不允许拦截,则会执行onInterceptTouchEvent,down事件肯定会执行这个方法,因为上面我们说了,down事件会重置FLAG_DISALLOW_INTERCEPT标记,此时intercepted由onInterceptTouchEvent决定

final boolean intercepted;
//如果是down事件或者mFirstTouchTarget不等于空
if (actionMasked == MotionEvent.ACTION_DOWN
        || mFirstTouchTarget != null) {
//并且当前View并没有设置不允许拦截,则会执行onInterceptTouchEvent,down事件肯定会执行这个方法,因为上面我们说了,down事件会重置FLAG_DISALLOW_INTERCEPT标记,此时intercepted由onInterceptTouchEvent决定
    final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
    if (!disallowIntercept) {
        intercepted = onInterceptTouchEvent(ev);
        ev.setAction(action); // restore action in case it was changed
    } else {
//如果不允许当前View拦截,则intercepted为false
        intercepted = false;
    }
} else {
    // There are no touch targets and this action is not an initial down
    // so this view group continues to intercept touches.
//如果没有子View处理此事件,也就是mFirstTouchTarget为空,并且不是down事件,也就是一次点击事件的后续事件,包括move和up事件,那么intercepted为true,表示当前View拦截了这个事件
    intercepted = true;
}

从这段代码可以看出,说明已经在注释中写的很清楚

继续往下看

TouchTarget newTouchTarget = null;
//如果没有取消,并且当前View没有拦截
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;
//如果是down事件
    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;
//如果newTouchTarget为空,并且有子View,则会遍历ViewGroup的所有子元素,然后判断子元素是否能够接受到点击事件。是否能够接收点击事件主要有两点衡量:子元素是否在播放动画和点击事件是否落在子元素的区域内。
        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 = buildOrderedChildList();
            final boolean customOrder = preorderedList == null
                    && isChildrenDrawingOrderEnabled();
            final View[] children = mChildren;
            for (int i = childrenCount - 1; i >= 0; i--) {
                final int childIndex = customOrder
                        ? getChildDrawingOrder(childrenCount, i) : i;
                final View child = (preorderedList == null)
                        ? children[childIndex] : preorderedList.get(childIndex);

               //......省略部分代码.......
//比较重要的是dispatchTransformedTouchEvent方法,是调用子元素的dispatchTouchEvent
                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();
//给mFirstTouchTarget赋值
                    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();
        }

     //...............省略部分代码...........
    }
}

上述代码是遍历子元素,判断是否有子元素处理事件,如果有,则给mFirstTouchTarget赋值,我们来看看

private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
        View child, int desiredPointerIdBits) {
    final boolean handled;

    // Canceling motions is a special case.  We don't need to perform any transformations
    // or filtering.  The important part is the action, not the contents.
    final int oldAction = event.getAction();
    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;
    }

    // Calculate the number of pointers to deliver.
    final int oldPointerIdBits = event.getPointerIdBits();
    final int newPointerIdBits = oldPointerIdBits & desiredPointerIdBits;

    // If for some reason we ended up in an inconsistent state where it looks like we
    // might produce a motion event with no pointers in it, then drop the event.
    if (newPointerIdBits == 0) {
        return false;
    }

    // If the number of pointers is the same and we don't need to perform any fancy
    // irreversible transformations, then we can reuse the motion event for this
    // dispatch as long as we are careful to revert any changes we make.
    // Otherwise we need to make a copy.
    final MotionEvent transformedEvent;
    if (newPointerIdBits == oldPointerIdBits) {
        if (child == null || child.hasIdentityMatrix()) {
            if (child == null) {
                handled = super.dispatchTouchEvent(event);
            } else {
                final float offsetX = mScrollX - child.mLeft;
                final float offsetY = mScrollY - child.mTop;
                event.offsetLocation(offsetX, offsetY);

                handled = child.dispatchTouchEvent(event);

                event.offsetLocation(-offsetX, -offsetY);
            }
            return handled;
        }
        transformedEvent = MotionEvent.obtain(event);
    } else {
        transformedEvent = event.split(newPointerIdBits);
    }

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

其实最核心的就是判断如果child == null,则调用super.dispatchTouchEvent,也就是View的dispatchTouchEvent,否则就会调用子元素的dispatchTouchEvent,将事件传递下去。我们再回到ViewGroup的dispatchTouchEvent中来,如果dispatchTransformedTouchEvent返回true,也就是有子元素处理了此down事件,那么就会在addTouchTarget中给mFirstTouchTarget赋值,否则,就会有如下判断

if (mFirstTouchTarget == null) {
    // No touch targets so treat this as an ordinary view.
    handled = dispatchTransformedTouchEvent(ev, canceled, null,
            TouchTarget.ALL_POINTER_IDS);
}

如果mFirstTouchTarget == null,也就是没有子元素处理,那么就会被当前元素处理(child参数传了null,在里面会递交给啊当前View处理)

那么目前down事件我们已经讲解完了,move事件和up事件也按照同样的道理往下传递

下面我们来看看View的dispatchTouchEvent处理

public boolean dispatchTouchEvent(MotionEvent event) {
 //.....................省略部分代码..............
    if (onFilterTouchEventForSecurity(event)) {
        //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;
        }
    }
//...................省略部分代码....................

    return result;
}

代码很简单,主要是判断是否设置onTouchListener事件,如果设置了,并且当前View是enable的,并且onTouchListener里面的onTouch返回了true,那么dispatchTouchEvent返回true,并且不会走onTouchEvent事件,说明onTouchListener的优先级比onTouchEvent高

如果当前View是disable的或者没有设置onTouchListener或者onTouch返回了false,那么就会调用onTouchEvent事件,根据onTouchEvent的返回值,决定当前View是否消耗此事件。

我们来看看onTouchEvent源码:

public boolean onTouchEvent(MotionEvent event) {
    final float x = event.getX();
    final float y = event.getY();
    final int viewFlags = mViewFlags;
    final int action = event.getAction();
//如果当前View是disabled的,那么就会根据当前View是否是Clickable或者longClickable来返回是否消耗此事件
    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);
    }

    if (mTouchDelegate != null) {
        if (mTouchDelegate.onTouchEvent(event)) {
            return true;
        }
    }
//如果当前View是enable,并且是Clickable或者longClickable等,就会进入如下判断
    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) {
                    // take focus if we don't have it already and we should in
                    // touch mode.
                    boolean focusTaken = false;
                    if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
                        focusTaken = requestFocus();
                    }

                    if (prepressed) {
                        // The button is being released before we actually
                        // showed it as pressed.  Make it show the pressed
                        // state now (before scheduling the click) to ensure
                        // the user sees it.
                        setPressed(true, x, y);
                   }

                    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)) {
//会在up事件中响应onClickListener事件
                                performClick();
                            }
                        }
                    }

                    if (mUnsetPressedState == null) {
                        mUnsetPressedState = new UnsetPressedState();
                    }

                    if (prepressed) {
                        postDelayed(mUnsetPressedState,
                                ViewConfiguration.getPressedStateDuration());
                    } else if (!post(mUnsetPressedState)) {
                        // If the post failed, unpress right now
                        mUnsetPressedState.run();
                    }

                    removeTapCallback();
                }
                mIgnoreNextUpEvent = false;
                break;

            case MotionEvent.ACTION_DOWN:
                mHasPerformedLongPress = false;

                if (performButtonActionOnTouchDown(event)) {
                    break;
                }

                // Walk up the hierarchy to determine if we're inside a scrolling container.
                boolean isInScrollingContainer = isInScrollingContainer();

                // For views inside a scrolling container, delay the pressed feedback for
                // a short period in case this is a scroll.
                if (isInScrollingContainer) {
                    mPrivateFlags |= PFLAG_PREPRESSED;
                    if (mPendingCheckForTap == null) {
                        mPendingCheckForTap = new CheckForTap();
                    }
                    mPendingCheckForTap.x = event.getX();
                    mPendingCheckForTap.y = event.getY();
                    postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
                } else {
                    // Not inside a scrolling container, so show the feedback right away
                    setPressed(true, x, y);
                    checkForLongClick(0);
                }
                break;

            case MotionEvent.ACTION_CANCEL:
                setPressed(false);
                removeTapCallback();
                removeLongPressCallback();
                mInContextButtonPress = false;
                mHasPerformedLongPress = false;
                mIgnoreNextUpEvent = false;
                break;

            case MotionEvent.ACTION_MOVE:
                drawableHotspotChanged(x, y);

                // Be lenient about moving outside of buttons
                if (!pointInView(x, y, mTouchSlop)) {
                    // Outside button
                    removeTapCallback();
                    if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
                        // Remove any future long press/tap checks
                        removeLongPressCallback();

                        setPressed(false);
                    }
                }
                break;
        }

        return true;
    }

    return false;
}

以上就是View的onTouchEvent,是否enable不决定当前View是否消耗此事件,clickable才是决定消耗事件的关键,如果当前View消耗了down事件,那么就会在up事件响应onClick事件,说明onClick的优先级比onTouchEvent低

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值