View事件分发

Android中,虽然View不属于四大组件,但它的作用可以堪比四大组件,不管是一个普通的视图,还是一个复杂的布局,都是依靠View来实现的。

与事件分发有关的方法

一个完整的手势包括4个操作

事件作用
ACTION_DOWN手指按下
ACTION_MOVE手指滑动
ACTION_UP手指抬起
ACTION_CANCEL事件被拦截

一次触摸屏幕的过程为DOWN->MOVE(若干个)->UP

在事件分发中,需要区分View和ViewGroup,虽然ViewGroup继承View,但一个事件的分发过程,是从一个ViewGroup开始的,ViewGroup 重写dispatchTounchEvent()方法,同时也只能在ViewGroup中处理onInterceptTouchEvent()方法

dispatchTounchEventonInterceptTouchEventonTounchEvent
Acvitity✔️✔️
ViewGroup✔️✔️✔️
View✔️✔️
  • dispatchTounchEvent负责将事件分发到当前View或其子View;
  • onInterceptTouchEvent只存在于ViewGroup中,用于拦截事件,优先级高于onTounchEvent;
  • onTounchEvent完成对事件的处理,可以拦截并消耗事件;

三者的关系可以根据如下伪代码来表示:

public boolean dispatchTouchEvent(Motion e){
     boolean result=false;
     if(onInterceptTouchEvent(e)){
     //如果当前View截获事件,那么事件就会由当前View处理,即调用onTouchEvent()
        result=onTouchEvent(e);
     }else{
        //如果不截获那么交给其子View来分发
        result=child.dispatchTouchEvent(e);
     }
     return result;
}

事件的处理流程

ViewGroup和View组成了一个树形结构,最顶层为Activity 的ViewGroup,下面有若干个ViewGroup节点,每个节点下面又又若干个ViewGroup节点或View节点

在这里插入图片描述
当一个Tounch事件到达根节点(Activity的ViewGroup)时,就会依次下发:ViewGroup遍历它的子View,调用每个View的dispatchTouchEvent方法,当子View为ViewGroup时,又会通过调用ViewGroup的dispatchTouchEvent方法继续调用其内部子View的dispatchTouchEvent方法。

下发过程分为如下几种情况

  1. 都不拦截、不消费
    在这里插入图片描述
  • 事件从Activity的dispatchTouchEvent开始传递,如果没有被拦截的话,会从上而下传递下去。
  • 在这个过程中ViewGroup可以通过onInterceptTouchEvent来拦截事件。返回true时表示要拦截,否则就会继续向下传递。
  • 如果这个过程没有被拦截,最底层的View也不消费(onTounchEvent返回false),则事件会反向传递,直到Activity的onTounchEvent。
  • 如果这个过程中没有View消费事件,那么接下来的DOWN和UP事件也不会传递 下去,直接由Activity处理。
  1. 底层View消费事件

在这里插入图片描述
事件被最底层View消费后,接下来的MOVE 和 UP 事件也会经过经过Vie wGroup的onInterceptTouchEvent,因为有可能被中间的ViewGroup拦截。

  1. 底层View消费DOWN,但是MOVE和UP事件被ViewGroup拦截

当事件被最底层View消费后,接下来的MOVE 和 UP 事件也会经过ViewGroup的onInterceptTouchEvent,因此也可能被中间的ViewGroup拦截。
在这里插入图片描述
这时CANCEL事件就会发挥作用,当某个事件被拦截,一开始处理DOWN事件的View就会收到CANCEL的事件,告诉View事件已经被拦截,而ViewGroup的onTounch不会接收到这个事件。后面的MOVE 、UP事件如果被拦截,就会被ViewGroup所消费。

源码分析
  • Activity、Window、PhoneWindow、DecorView之间的关系
public class Activity extends ContextThemeWrapper {
    private Window mWindow;
}

查看Activity的源码,每个Activity都会对应一个Window。Window作为一个抽象类,只有一个实现类PhoneWindow。

public class PhoneWindow extends Window {
    private DecorView mDecor;
}

PhoneWindow内持有一个DecorView

private final class DecorView extends FrameLayout {

}

  • 事件从上而下传递,分析也从Activity开始:
    Activity
public boolean dispatchTouchEvent(MotionEvent ev) {
    if (ev.getAction() == MotionEvent.ACTION_DOWN) {
        onUserInteraction();
    }
    if (getWindow().superDispatchTouchEvent(ev)) {
        return true;
    }
    return onTouchEvent(ev);
}

如果时DOWN事件的话,则会调用onUserInteraction()这个方法。想知道用户何时于屏幕发生交互时,可以重写此方法。

然后调用getWindow().superDispatchTouchEvent(ev),如果返回为false,则给Activity.onTounchEvent消费。(getWindow()的superDispatchTouchEvent将事件从上而下传递下去,如果一直没人处理时,则才会给Activity消费)
这里的getWindow().superDispatchTouchEvent(ev)调用的是PhoneWindow的superDispatchTouchEvent,代理调用了DecorView的superDispatchTouchEvent。

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

DecorView:

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

DecorView调用父类FragmentLayout的dispatchTounchEvent,然后FragmentLayout调用ViewGroup。到这里事件就从Activity传递到ViewGroup了

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

DOWN事件意味着新的手势开始,所以当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;
}

这段代码判断是否要拦截当前事件。如果为DOWN或者mFirstTouchTarget != null时,根据FLAG_DISALLOW_INTERCEPT标记(子View可以通过requestDisallowInterceptTouchEvent来设置)为来判断当前ViewGroup是否允许拦截,若子View调用了requestDisallowInterceptTouchEvent,则不允许拦截。否则询问当前ViewGroup是否要拦截。

这里我们总结下一个ViewGroup如何才能拦截一个事件。

  1. actionMasked == MotionEvent.ACTION_DOWN || mFirstTouchTarget != null 并且子View没有设置requestDisallowInterceptTouchEvent。对于DOWN事件来说,即使子View已经调用requestDisallowInterceptTouchEvent,也会去询问当前ViewGroup,因为在DOWN事件会通过resetTouchState()重置状态。因此留意下,requestDisallowInterceptTouchEvent若使用时机不正确将无法发挥作用。
  2. 不为DOWN事件并且mFirstTouchTarget为空。当事件被子View处理时,mFirstTouchTarget会被赋值,mFirstTouchTarget为空时意味着事件是由ViewGroup处理的。因此当MOVE或者UP到来时,事件直接被ViewGroup处理。
/**
*第一部分
*/
// 检查是否为cancel
final boolean canceled = resetCancelNextUpFlag(this) || actionMasked == MotionEvent.ACTION_CANCEL;
// 没有intercepted或者canceled
if (!canceled && !intercepted) {

    // ......

    if (actionMasked == MotionEvent.ACTION_DOWN
        || (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)
        || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {

        // ......

        final int childrenCount = mChildrenCount;
        if (newTouchTarget == null && childrenCount != 0) {
            final float x = ev.getX(actionIndex);
            final float y = ev.getY(actionIndex);

            // 遍历子View,顺序从上到下,后添加的View先询问
            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);

                // ......

                // 检查View的visibility、是否在播放动画、触摸点是否在view视图内
                if (!canViewReceivePointerEvents(child) || !isTransformedTouchPointInView(x, y, child, null)) {                                     
                    ev.setTargetAccessibilityFocus(false);
                    continue;
                }
                // 寻找此子View是否在mFirstTouchTarget链中,若存在,则已经找到View
                newTouchTarget = getTouchTarget(child);
                if (newTouchTarget != null) {
                    newTouchTarget.pointerIdBits |= idBitsToAssign;
                    break;
                }

                // ......

                // dispatchTransformedTouchEvent()内部调用子View的dispatchTouchEvent去分发。
                // 如果返回true,则代表事件被子View消费,newTouchTarget就会被添加到mFirstTouchTarget链中
                if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
                    // ......
                    newTouchTarget = addTouchTarget(child, idBitsToAssign);
                    alreadyDispatchedToNewTouchTarget = true;
                    break;
                }

            }
            // ......
       }

       // ......
   }
}
/**
*第二部分
*/
if (mFirstTouchTarget == null) {
    // mFirstTouchTarget为空,表明没有子View接收事件,则分发给当前ViewGroup
    handled = dispatchTransformedTouchEvent(ev, canceled, null, TouchTarget.ALL_POINTER_IDS);
} else {
    // 若DOWN事件已经被View处理,则mFirstTouchTarget不为空,MOVE和UP事件开始分发
    TouchTarget predecessor = null;
    TouchTarget target = mFirstTouchTarget;
    while (target != null) { // 循环变量mFirstTouchTarget,对于单指操作只有一个touchTarget
        final TouchTarget next = target.next;
        // 上面已经分发过了,无需再分发
        if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
            handled = true;
        } else {
            final boolean cancelChild = resetCancelNextUpFlag(target.child) || intercepted;
            // 若cancelChild为false,则将事件传递给子View。
            // 若cancelChild为true,分发CANCEL事件给子View。
            // 一个常见的例子就是,DOWN事件是由子View接收的,当ViewGroup尝试拦截MOVE事件(onInterceptTouchEvent中返回		 true)时,子View会收到一个CANCEL事件,就如我们上面的例子所介绍的。
            if (dispatchTransformedTouchEvent(ev, cancelChild, target.child, target.pointerIdBits)) {
                handled = true;
            }
            // 如果cancelChild,清空所有的touchTarget,接下来的所有TouchEvent都被自己的onTouchEvent来处理
            if (cancelChild) {
                if (predecessor == null) {
                    mFirstTouchTarget = next;
                } else {
                    predecessor.next = next;
                }
                target.recycle();
                target = next;
                continue;
            }
        }
        predecessor = target;
        target = next;
    }
}

// 单指操作时,若为UP事件或者被CANCEL时,重置触摸状态(包括mFirstTouchTarget)
if (canceled || actionMasked == MotionEvent.ACTION_UP || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
    resetTouchState();
}

// 此View是否消费事件
return handled;

我们来分析主要逻辑,忽略其他因素

  1. 如果ViewGroup不拦截事件或者事件没有被CANCELED并且为DOWN事件时,会遍历ViewGroup的所有子View。在遍历过程中会判断子元素是否能够接收事件。canViewReceivePointerEvents判断子元素是否可见以及判断是否在播放动画中,isTransformedTouchPointInView判断事件是否落在子View的区域内。然后dispatchTransformedTouchEvent去分发事件给子View,如果返回true,则事件被子View消费,mFirstTouchTarget会被赋值。
  2. 在第二部分开始会根据mFirstTouchTarget判断分发事件。根据上一步我们知道如果DOWN事件被子View消费时,mFirstTouchTarget不为空。所以mFirstTouchTarget为空有两种情况:
    (1). DOWN事件被拦截或者DOWN事件没有被子View处理时;
    (2). 如果DOWN事件被子View处理,但是中途有事件被拦截时,会清空mFirstTouchTarget,会导致后续的事件在判断时mFirstTouchTarget都为空。
  3. 如果mFirstTouchTarget为空,会调用dispatchTransformedTouchEvent自己去处理事件。
    dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,View child, int desiredPointerIdBits)会根据第三个参数child是否为空做不同的处理:
    (1). 当child为空时会调用自己的父类的dispatchTouchEvent,这里的父类实际就是View,所以相当于把自己当作View去处理事件;
    (2). 当child不为空时会调用child的dispatchTouchEvent,完成事件向下分发。
  4. 如果mFirstTouchTarget不为空,根据alreadyDispatchedToNewTouchTarget判断事件是否已经分发。如果没有分发,被ViewGroup拦截时,此时会分发一个CANCEL事件给子View并清空mFirstTouchTarget,此后的事件都由ViewGroup处理;没有被拦截则正常分发。到这里ViewGroup分发流程就结束了
onInterceptTouchEvent
public boolean onInterceptTouchEvent(MotionEvent ev) {
    if (ev.isFromSource(InputDevice.SOURCE_MOUSE)
        && ev.getAction() == MotionEvent.ACTION_DOWN
        && ev.isButtonPressed(MotionEvent.BUTTON_PRIMARY)
        && isOnScrollbarThumb(ev.getX(), ev.getY())) {
        return true;
    }
    return false;
}

onInterceptTouchEvent比较简单,if里面判断在一般的触摸事件里都是false的,因为isFromSource判断事件是不是来自鼠标。
即使子View调用requestDisallowInterceptTouchEvent,DOWN事件还是会经过onInterceptTouchEvent,因为在dispatchTouchEvent时会将这个标记重置。

onTouchEvent

ViewGroup没有重写这个方法,因此调用ViewGroup的onTouchEvent实则为调用View的。

View

从上面知道,事件会一直递归下去,直到找到合适的View处理事件。当ViewGroup找不到子View来处理时,会调用dispatchTransformedTouchEvent让自己处理事件,传入的child参数为null,最终会调用父类的dispatchTouchEvent方法。

dispatchTouchEvent
public boolean dispatchTouchEvent(MotionEvent event) {

    boolean result = false;

    // ......

    if (onFilterTouchEventForSecurity(event)) {
        // ......

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

View的事件处理比较简单,先判断是否有设置OnTouchListener,如果OnTouchListener返回true,则事件被消费了。若OnTouchListener返回false,会调用onTouchEvent来得到最终结果。这里我们可以知道一点:OnTouchListener优先级比onTouchEvent高
需要ENABLED的View设置OnTouchListener才有效果,而即使DISABLED的View在onTouchEvent也能接收到事件。

onTouchEvent

首先当View处于DISABLED状态时,如果是CLICKABLE、CONTEXT_CLICKABLE或者LONG_CLICKABLE也会消费事件。然后判断View是否有设置TouchDelegate,这个可以用来扩大View的点击事件。

final float x = event.getX();
final float y = event.getY();
final int viewFlags = mViewFlags;
final int action = event.getAction();

if ((viewFlags & ENABLED_MASK) == DISABLED) {
    if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
        setPressed(false);
    }
    // DISABLED的View如果是CLICKABLE、CONTEXT_CLICKABLE或者LONG_CLICKABLE也会消费事件
    return (((viewFlags & CLICKABLE) == CLICKABLE
        || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
        || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE);
}
// TouchDelegate用于扩大View的点击范围
if (mTouchDelegate != null) {
    if (mTouchDelegate.onTouchEvent(event)) {
        return true;
    }
}

接下来根据action的类型做不同处理,这里我们按照普通的触摸顺序进行分析,DOWN -> MOVE -> UP以及CANCEL。在分析之前我们需要知道两种状态:

  • prepressed:若View处于可滑动的父布局中时,预防滚动事件,将界面变化延时展示。在这个延时的过程中处于prepressed状态。标记为PFLAG_PREPRESSED。
  • pressed:DOWN事件发生时处于pressed状态,若View处于可滑动的父布局中时,则需要延时后才处于。标记为PFLAG_PRESSED。
DOWN事件:
case MotionEvent.ACTION_DOWN:
    mHasPerformedLongPress = false;

    // ......

    // 一层层向上遍历判断是否处于可滑动的父布局之中。
    boolean isInScrollingContainer = isInScrollingContainer();

    // 若处于可滑动的布局之中,延迟点击界面状态的变化,以防是滚动事件。
    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, x, y);
    }
    break;

mHasPerformedLongPress表示是否为长按,初始化为false。通过一层层向上遍历判断View是否处于可滑动的父布局中。

如果不是的话,直接将界面变化反馈给用户。如果是LONG_CLICKABLE的话,发送一个延迟消息CheckForLongPress检测长按状态,这个时间默认为500ms;

如果处于滑动的父布局的话,为了防止是滚动的情况,需要延迟反馈界面变化给用户。因此标记为prepressed状态,并发送一个延迟为100ms的消息CheckForTap,100ms后将设置为pressed状态,并再发送一个延迟为400ms的消息CheckForLongPress检测长按状态。也就是说,只有按住500ms才会认为是长按。

进入CheckForLongPress看看:

private final class CheckForLongPress implements Runnable {
    private int mOriginalWindowAttachCount;
    private float mX;
    private float mY;

    @Override
    public void run() {
        if (isPressed() && (mParent != null)
            && mOriginalWindowAttachCount == mWindowAttachCount) {
            if (performLongClick(mX, mY)) {
                mHasPerformedLongPress = true;
            }
        }
    }

    // ......
}

CheckForLongPress里面调用了performLongClick,performLongClick里调用了LongClickListener,如果onLongClick返回true的话,把mHasPerformedLongPress标记为true。

MOVE事件:
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;

如果事件坐标超出View,则移除CheckForTap。如果处于pressed状态,则移除CheckForLongPress并且刷新界面状态。

UP事件:
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)) {
                    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;

当UP事件发生时,若处于pressed或者prepressed状态,则获取焦点。若处于prepressed状态时发生了UP事件则刷新界面,确保用户能得到这次反馈。如果还没进入长按的状态,则调用performClick。很显然,在performClick里去执行OnClickListener的onClick方法。最后重置界面状态。

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

CANCEL事件主要做了重置的操作。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值