美文网首页
Android事件分发

Android事件分发

作者: 超人TIGA | 来源:发表于2020-09-03 23:22 被阅读0次

面试一般都会问到事件分发机制,而且很多时候自定义view也有可能需要用到,这里就说一下事件分发。
事件:其实就是用户的操作,例如按下、滑动、抬起等动作,一般一个完整的用户操作,是指按下-滑动(0次或者多次)-抬起。
事件分发:就是对于上面的事件进行处理,达到用户想要的效果,例如点击一个按钮弹出一个toast,滑动一个列表等。

一般我们的APP都是由activity、fragment和各种各样的view来组成的,而其中activity更是其他两者的主要载体,同时看源码可以知道,当用户点击屏幕,首先处理的也是activity。

public boolean dispatchTouchEvent(MotionEvent ev) {
        //先拦截按下事件
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            onUserInteraction();
        }
        //如果其他地方消耗了事件,返回true
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        //如果事件没有被window的dispatchTouchEvent方法消耗,则触发activity中的onTouchEvent方法的返回值
        return onTouchEvent(ev);
    }

这里的逻辑十分简单,先判断down事件并触发onUserInteraction(),之后就是把事件传递给window处理,根据处理结果决定是否再交给activity的onTouchEvent()处理。

public void onUserInteraction() {
    }

onUserInteraction是一个空方法,对事件分发无影响。然后看一下window中的事件分发源码:

public abstract class Window {
    /**
     * Used by custom windows, such as Dialog, to pass the touch screen event
     * further down the view hierarchy. Application developers should
     * not need to implement or call this.
     *
     */
    public abstract boolean superDispatchTouchEvent(MotionEvent event);
}

这里看到是一个抽象方法,所以我们需要找到实现window的子类,而PhoneWindow就是window的唯一实现子类,那继续到phoneWindow中找:

public class PhoneWindow extends Window implements MenuBuilder.Callback {
    @Override
    public boolean superDispatchTouchEvent(MotionEvent event) {
        return mDecor.superDispatchTouchEvent(event);
    }
}

这里能看到是交给了decorView处理,而decorView就熟悉了,就是我们布局层的父布局。

public class DecorView extends FrameLayout implements RootViewSurfaceTaker, WindowCallbacks {
    public boolean superDispatchTouchEvent(MotionEvent event) {
        return super.dispatchTouchEvent(event);
    }
}

而在decorView中,是继续把事件交给父类处理,而这里的父类,就是FrameLayout,也就是ViewGroup去实现,由ViewGroup的结果决定事件是否继续给activity处理。

大概流程为: image.png
这里就是暂时抛开viewGroup和子view的事件分发,关于activity层对于事件分发的逻辑;

那接下来我们开始看看viewGroup中是怎么处理事件分发的。
先看ViewGroup中的disPatchTouchEvent:

public abstract class ViewGroup extends View implements ViewParent, ViewManager {
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
            /**省略部分代码**/
            // 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();
            }

            // 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;
            }
            /**省略部分代码**/
      }
}

首先会判断是否按下事件,是的话就进行状态清理和重置。然后就根据(actionMasked == MotionEvent.ACTION_DOWN|| mFirstTouchTarget != null)来判断,mFirstTouchTarget的作用就是当找到消耗事件的子view时,mFirstTouchTarget指向这个子view。事件是ACTION_DOWN,一开始一定是按下事件所以能进去if语句的逻辑。然后到这里:

final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;

FLAG_DISALLOW_INTERCEPT是一个标志位,作用就是控制除了ACTION_DOWN以外的动作,其他动作是否交给ViewGroup处理。FLAG_DISALLOW_INTERCEPT会在子View消耗事件的时候改变它的值,使得后面的动作不再需要onInterceptTouchEvent(ev)来处理,intercepted为false。
到这里为止,主要就是为了得到intercepted的值,进行下一步的事件处理。如果不进行拦截,那就是交给子View处理事件,继续往下看代码:

                    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;
                        //遍历子View
                        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;
                            }
                            //判断view是否能接受点击事件
                            //判断点击区域是不是在view的范围内
                            //其中有一项不符合,就标记不合适并继续找下一个
                            if (!child.canReceivePointerEvents()
                                    || !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);
                                //设置已经处理了Down事件
                                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();
                    }

这里能看到,ViewGroup会对所有子View进行遍历,根据view是否能响应点击事件和事件点击的坐标是否在view的区域内来判断子view能不能接受这个事件,如果能就调用dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)方法,根据这方法的返回值,来判断事件是否被消耗,这方法的主要逻辑,其实就是调用子View的dispatchTouchEvent()方法:

    private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
            View child, int desiredPointerIdBits) {
        
        /**省略部分代码*/
        
        // 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;
}

根据子view的dispatchTouchEvent方法的返回值,如果事件被子View消耗(返回true),那就会alreadyDispatchedToNewTouchTarget = true,设置事件已经被消耗,并调用addTouchTarget(child, idBitsToAssign)方法,给mFirstTouchTarget赋值,再回头看viewGroup一开始的事件拦截,就会发现mFirstTouchTarget!=null为true了。

    /**
     * Adds a touch target for specified child to the beginning of the list.
     * Assumes the target child is not already present.
     */
    private TouchTarget addTouchTarget(@NonNull View child, int pointerIdBits) {
        final TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
        target.next = mFirstTouchTarget;
        mFirstTouchTarget = target;
        return target;
    }

这方法的主要目的就是将mFirstTouchTarget 指向消耗事件的View。到这里都是基于事件被某个子View消耗的逻辑。如果没有子View能把这个事件消耗掉,那就继续交给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);
            }

由于上面的遍历子View逻辑找不到对应的view来消耗事件,所以mFirstTouchTarget为null,所以就执行dispatchTransformedTouchEvent(ev, canceled, null,TouchTarget.ALL_POINTER_IDS)方法。其实这个方法前面已经有提到,区别只是这里第3个参数传了null,也就是child为null。

            if (child == null) {
                handled = super.dispatchTouchEvent(event);
            }

ViewGroup的父类也是View,所以其实就是交给View的dispatchTouchEvent方法来处理这个事件。
ViewGroup的大概流程是:


image.png

最后我们就是看具体View的事件处理代码了。先从View的dispatchTouchEvent方法开始看起:

/**
     * Pass the touch screen motion event down to the target view, or this
     * view if it is the target.
     *
     * @param event The motion event to be dispatched.
     * @return True if the event was handled by the view, false otherwise.
     */
    public boolean dispatchTouchEvent(MotionEvent event) {
        //省略部分代码
        boolean result = false;
        //省略部分代码
        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;
            }
        }
        //省略部分代码
        return result;
    }

除开省略的代码(主要是一些状态的设置和对于列表的滚动控制),可以看到onFilterTouchEventForSecurity(event),这方法判断的就是这个这个view是否被挡住了,false就是被挡住了。

public boolean onFilterTouchEventForSecurity(MotionEvent event) {
        //noinspection RedundantIfStatement
        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
            // Window is obscured, drop this touch.
            return false;
        }
        return true;
    }

然后往下看,就是一个多条件的if判断,其中有一个条件是li.mOnTouchListener.onTouch(this, event),这里就是判断onTouchListener的onTouch方法,如果返回了true(例如自定义view我们返回true),那就给result赋值为true。

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

下面接着的是onTouchEvent(event)方法:

            if (!result && onTouchEvent(event)) {
                result = true;
            }

看条件可以知道,onTouch方法的优先级会比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();

        final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE
                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
                || (viewFlags & CONTEXT_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;
        }
        if (mTouchDelegate != null) {
            if (mTouchDelegate.onTouchEvent(event)) {
                return true;
            }
        }

        if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
            switch (action) {
                case MotionEvent.ACTION_UP:
                    //省略部分代码
                    if (!post(mPerformClick)) {
                        performClickInternal();
                    }
                    //省略部分代码
                    break;

                case MotionEvent.ACTION_DOWN:
                    //省略部分代码
                    break;

                case MotionEvent.ACTION_CANCEL:
                    //省略部分代码
                    break;

                case MotionEvent.ACTION_MOVE:
                    //省略部分代码
                    break;
            }

            return true;
        }

        return false;
    }

clickable的值只要CLICKABLE、LONG_CLICKABLE、CONTEXT_CLICKABLE符合其中一个就为true。当为ACTION_UP时,触发performClickInternal方法,其作用为调用View的performClick()方法。


    /**
     * Entry point for {@link #performClick()} - other methods on View should call it instead of
     * {@code performClick()} directly to make sure the autofill manager is notified when
     * necessary (as subclasses could extend {@code performClick()} without calling the parent's
     * method).
     */
    private boolean performClickInternal() {
        // Must notify autofill manager before performing the click actions to avoid scenarios where
        // the app has a click listener that changes the state of views the autofill service might
        // be interested on.
        notifyAutofillManagerOnClick();

        return performClick();
    }

而performClick方法,其实就是调用我们平时设置的onClickListener的onClick方法。

    /**
     * Call this view's OnClickListener, if it is defined.  Performs all normal
     * actions associated with clicking: reporting accessibility event, playing
     * a sound, etc.
     *
     * @return True there was an assigned OnClickListener that was called, false
     *         otherwise is returned.
     */
    // NOTE: other methods on View should not call this method directly, but performClickInternal()
    // instead, to guarantee that the autofill manager is notified when necessary (as subclasses
    // could extend this method without calling super.performClick()).
    public boolean performClick() {
        // We still need to call this method to handle the cases where performClick() was called
        // externally, instead of through performClickInternal()
        notifyAutofillManagerOnClick();

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

流程图如下:


image.png

到这里,就已经把整个事件分发的流程讲解了一遍了。

相关文章

网友评论

      本文标题:Android事件分发

      本文链接:https://www.haomeiwen.com/subject/sysnjktx.html