Android事件分发、事件拦截、事件处理分析

事件机制在android开发中是比较常见的场景,比如:点击、双击、长按、触摸等,当然提到最多的就是View和ViewGroup的事件处理机制,事件处理机制包括:事件分发、事件拦截、事件处理,View包含:事件分发和事件处理,ViewGroup包含:事件分发、事件拦截、事件处理;接下来就看下当用于点击或者触摸默认控件(图标)时事件的流程走向吧。
Activity中就包含一个自定义的LinearLayout和一个自定的View,重写了Activity中的dispatchTouchEvent和onTouchEvent方法,




    


@Override
    public boolean onTouchEvent(MotionEvent event) {
        int action = event.getAction();
        if (action == MotionEvent.ACTION_DOWN) {
            Log.d(TAG, "事件处理----onTouchEvent----按下了");
        } else if (action == MotionEvent.ACTION_UP) {
            Log.d(TAG, "事件处理----onTouchEvent----抬起了");
        } else if (action == MotionEvent.ACTION_MOVE) {
            Log.d(TAG, "事件处理----onTouchEvent----移动了");
        }
        //返回true或者false 或者系统的默认值 都代表对事件的消费,
        //不过返回false的话不会有MotionEvent.ACTION_MOVE
        return super.onTouchEvent(event);
    }
@Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        int action = ev.getAction();
        if (action == MotionEvent.ACTION_DOWN) {
            Log.d(TAG, "事件处理----dispatchTouchEvent----按下了");
        } else if (action == MotionEvent.ACTION_UP) {
            Log.d(TAG, "事件处理----dispatchTouchEvent----抬起了");
        } else if (action == MotionEvent.ACTION_MOVE) {
            Log.d(TAG, "事件处理----dispatchTouchEvent----移动了");
        }
        //这里如果返回true或者false就不会对事件进行分发,后面的ViewGroup和View就响应不到事件了
        return super.dispatchTouchEvent(ev);
    }

自定义ViewGroup中重写了dispatchTouchEvent、onTouchEvent、onTnterceptTouchEvent方法,

public class MyViewGroup extends LinearLayout {
    private static final String TAG=MyViewGroup.class.getSimpleName();
    public MyViewGroup(Context context) {
        this(context,null);
    }

    public MyViewGroup(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,-1);
    }

    public MyViewGroup(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setOrientation(LinearLayout.VERTICAL);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int action = event.getAction();
        if (action == MotionEvent.ACTION_DOWN) {
            Log.d(TAG, "事件处理----onTouchEvent----按下了");
        } else if (action == MotionEvent.ACTION_UP) {
            Log.d(TAG, "事件处理----onTouchEvent----抬起了");
        } else if (action == MotionEvent.ACTION_MOVE) {
            Log.d(TAG, "事件处理----onTouchEvent----移动了");
        }
        //事件处理
        return super.onTouchEvent(event);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        int action = ev.getAction();
        if (action == MotionEvent.ACTION_DOWN) {
            Log.d(TAG, "事件处理----dispatchTouchEvent----按下了");
        } else if (action == MotionEvent.ACTION_UP) {
            Log.d(TAG, "事件处理----dispatchTouchEvent----抬起了");
        } else if (action == MotionEvent.ACTION_MOVE) {
            Log.d(TAG, "事件处理----dispatchTouchEvent----移动了");
        }
        //事件分发
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        Log.d(TAG,"事件处理----onInterceptTouchEvent");
        //事件拦截
        //如果返回true,代表对事件进行拦截 
        return super.onInterceptTouchEvent(ev);
    }
}

自定义View重写了dispatchTouchEvent、onTouchEvent方法,

public class MyView extends AppCompatTextView {
    private static final String TAG = MyView.class.getSimpleName();

    public MyView(Context context) {
        this(context, null);
    }

    public MyView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, -1);
    }

    public MyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int action = event.getAction();
        if (action == MotionEvent.ACTION_DOWN) {
            Log.d(TAG, "事件处理----onTouchEvent----按下了");
        } else if (action == MotionEvent.ACTION_UP) {
            Log.d(TAG, "事件处理----onTouchEvent----抬起了");
        } else if (action == MotionEvent.ACTION_MOVE) {
            Log.d(TAG, "事件处理----onTouchEvent----移动了");
        }
        //事件处理
        return super.onTouchEvent(event);
    }
    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        int action = event.getAction();
        if (action == MotionEvent.ACTION_DOWN) {
            Log.d(TAG, "事件处理----dispatchTouchEvent----按下了");
        } else if (action == MotionEvent.ACTION_UP) {
            Log.d(TAG, "事件处理----dispatchTouchEvent----抬起了");
        } else if (action == MotionEvent.ACTION_MOVE) {
            Log.d(TAG, "事件处理----dispatchTouchEvent----移动了");
        }
        //事件分发
        return super.dispatchTouchEvent(event);
    }
}
dispatchTouchEvent  事件分发
onTouchEvent  事件处理
onInterceptTouchEvent  事件拦截

上面重写的方法的返回值没有做修改,返回的都是系统默认的值,看下打印的日志输出,

事件机制.png

首先响应的是activity中的方法,然后是ViewGroup,最后才是点击的View控件,直到事件被消费掉,通过之前对setContentView源码的分析得知,用户看的界面,依次为:

PhoneWindow(Window)--->DecorView(FrameLayout)--->R.id.content(系统布局容器)--->自定义的布局容器--->自定义的View控件

所以得到:

其实就是ViewGroup一直将事件传递分发下去直到事件被拦截或者消费掉为止。

既然这样的话,如果activity中的dispatchTouchEvent返回true或者false的话,就不会将事件分发下去,后面的ViewGroup和View也就响应不到事件了,


事件机制0.png

这个是返回true,返回false少了MotionEvent.ACTION_MOVE,activity中onTouchEvent返回true或者false 或这系统默认值,都是对事件进行消费,返回false会少了MotionEvent.ACTION_MOVE。在activity的dispatchTouchEvent中可以看到会调用Window中的superDispatchTouchEvent方法

public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            //在activity中可以重写该方法,执行一些action_down后的逻辑
            onUserInteraction();
        }
    //调用window中的方法
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
    //调用onTouchEvent方法,判断事件是否被消费掉 
    //如果没有消费掉就继续分发  如果消费掉了就停止分发
        return onTouchEvent(ev);
    }
@Override
    public boolean superDispatchTouchEvent(MotionEvent event) {
        //调用了DecorView中的superDispatchTouchEvent方法
        return mDecor.superDispatchTouchEvent(event);
    }

在PhoneWindow中看到接着调用到了DecorView中的superDispatchTouchEvent方法,DecorView其实是继承自ViewGroup的,那其实调用的就是ViewGroup中的dispatchTouchEvent方法,

public boolean superDispatchTouchEvent(MotionEvent event) {
    //DecorView中调用父类ViewGroup中的dispatchTouchEvent方法
        return super.dispatchTouchEvent(event);
    }
@Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
        }

        // 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);
        }
        //用于标记dispatchTouchEvent的返回值
        boolean handled = false;
        //过滤掉一些事件处理,true代表需要处理  false代表过滤
        if (onFilterTouchEventForSecurity(ev)) {
            //获取当前对应的事件类型 比如 是down还是up等
            final int action = ev.getAction();
            //获取对应事件类型的mask
            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.
                //取消和清除之前的touchTarget  在这里mFirstTouchTarget会被设置为null
                cancelAndClearTouchTargets(ev);
                //恢复事件的状态
                resetTouchState();
            }
            //标识检查时间是否被拦截
            // Check for interception.
            final boolean intercepted;
            if (actionMasked == MotionEvent.ACTION_DOWN
                    || mFirstTouchTarget != null) {
                //FLAG_DISALLOW_INTERCEPT 是否允许拦截的标识
                final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
                if (!disallowIntercept) {
                    //交由onInterceptTouchEvent 来觉得是否进行拦截 可以在子类中重写该方法 进行事件的拦截
                    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.
                //没有触摸的目标,并且不是最初的 就直接拦截该view
                intercepted = true;
            }

            // 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);
            }
            //检测事件是否被取消
            // Check for cancelation.
            final boolean canceled = resetCancelNextUpFlag(this)
                    || actionMasked == MotionEvent.ACTION_CANCEL;

            // Update list of touch targets for pointer down, if needed.
            final boolean isMouseEvent = ev.getSource() == InputDevice.SOURCE_MOUSE;
            final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0
                    && !isMouseEvent;
            //定义事件目标实例对象
            TouchTarget newTouchTarget = null;
            boolean alreadyDispatchedToNewTouchTarget = false;
            //如果事件没有被取消 并且没有被拦截 这个时候根据需要进行事件的分发和处理
            if (!canceled && !intercepted) {
                // If the event is targeting accessibility 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;

                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);
                    //获取childview的数量
                    final int childrenCount = mChildrenCount;
                    //如果事件目标为null 同事布局中有子view
                    if (newTouchTarget == null && childrenCount != 0) {
                        //获取事件目标在屏幕中的位置
                        final float x =
                                isMouseEvent ? ev.getXCursorPosition() : ev.getX(actionIndex);
                        final float y =
                                isMouseEvent ? ev.getYCursorPosition() : ev.getY(actionIndex);
                        // Find a child that can receive the event.
                        // Scan children from front to back.
                        //寻找对应事件的view,从前到后的方式遍历view
                        //构建事件触摸分发处理子view列表
                        final ArrayList preorderedList = buildTouchDispatchChildList();
                        final boolean customOrder = preorderedList == null
                                && isChildrenDrawingOrderEnabled();
                        //获取容器中view
                        final View[] children = mChildren;
                        //进行对布局中view的遍历
                        for (int i = childrenCount - 1; i >= 0; i--) {
                            final int childIndex = getAndVerifyPreorderedIndex(
                                    childrenCount, i, customOrder);
                            //获取对应位置的view,如果不是事件对应的view 就跳过去
                            final View child = getAndVerifyPreorderedView(
                                    preorderedList, children, childIndex);
                            if (!child.canReceivePointerEvents()
                                    || !isTransformedTouchPointInView(x, y, child, null)) {
                                continue;
                            }
                            //获取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;
                            }
                            //重置一些取消的标识
                            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();
                    }

                    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;
                    }
                }
            }
            //事件分发目标
            // Dispatch to touch targets.
            if (mFirstTouchTarget == null) {
                //第一次 或者处理完一次后事件分发目标肯定是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;
                }
            }

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

        if (!handled && mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onUnhandledEvent(ev, 1);
        }
        return handled;
    }

在执行事件分发逻辑时,ViewGroup会去判断是否要对View进行事件拦截,如果进行了拦截,就没有后面View的事件分发和处理了,

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

事件拦截默认返回false,是不拦截的,如果需要拦截view的事件,在对应的布局容器中重写onInterceptTouchEvent返回true,如果事件没有被取消,也没有被拦截,第一次mFirstTouchTarget肯定是null的,就会调用

handled = dispatchTransformedTouchEvent(ev, canceled, null,TouchTarget.ALL_POINTER_IDS);

mFirstTouchTarget是一个TouchTarget实例对象,是用于描述和存储事件目标view的,使用的是单项链表的结构,

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) {
                //view为null 直接调用ViewGroup的父类的事件分发
                handled = super.dispatchTouchEvent(event);
            } else {
                //调用view child的事件分发
                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 {
                    //计算view事件的坐标
                    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) {
            //第一次的时候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或者ViewGroup的父类的dispatchTouchEvent去进行事件分发的处理,

public boolean dispatchTouchEvent(MotionEvent event) {
        // 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);
        }
    //定义事件分发的结果标识
        boolean result = false;

        if (mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
        }

        final int actionMasked = event.getActionMasked();
        if (actionMasked == MotionEvent.ACTION_DOWN) {
            // Defensive cleanup for new gesture
            //停止正在的滚动
            stopNestedScroll();
        }

        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;
            }
            //如果result为false 会通过onTouchEvent看看对该事件有没有进行消费
            if (!result && onTouchEvent(event)) {
                result = true;
            }
        }

        if (!result && mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
        }

        // Clean up after nested scrolls if this is the end of a gesture;
        // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
        // of the gesture.
        if (actionMasked == MotionEvent.ACTION_UP ||
                actionMasked == MotionEvent.ACTION_CANCEL ||
                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
            stopNestedScroll();
        }

        return result;
    }

ListenerInfo是一个静态的管理一些了事件监听的类,其中就包含了OnTouchListener,可以给对应的View或者ViewGroup设置OnTouchListener来达到事件消费的目的,

findViewById(R.id.view_id).setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                //默认返回false 改为返回true 代表消费当前事件
                return true;
            }
        });

如果并没有设置OnTouchListener就会通过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:
                    mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
                    if ((viewFlags & TOOLTIP) == TOOLTIP) {
                        handleTooltipUp();
                    }
                    if (!clickable) {
                        removeTapCallback();
                        removeLongPressCallback();
                        mInContextButtonPress = false;
                        mHasPerformedLongPress = false;
                        mIgnoreNextUpEvent = false;
                        break;
                    }
                    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.
                                //创建PerformClick实例
                                if (mPerformClick == null) {
                                    mPerformClick = new PerformClick();
                                }
                                if (!post(mPerformClick)) {
                                    //调用该方法通过点击事件的触发来进行事件的消费
                                    performClickInternal();
                                }
                            }
                        }

                        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:
                    if (event.getSource() == InputDevice.SOURCE_TOUCHSCREEN) {
                        mPrivateFlags3 |= PFLAG3_FINGER_DOWN;
                    }
                    mHasPerformedLongPress = false;

                    if (!clickable) {
                        checkForLongClick(
                                ViewConfiguration.getLongPressTimeout(),
                                x,
                                y,
                                TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__LONG_PRESS);
                        break;
                    }

                    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(
                                ViewConfiguration.getLongPressTimeout(),
                                x,
                                y,
                                TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__LONG_PRESS);
                    }
                    break;

                case MotionEvent.ACTION_CANCEL:
                    if (clickable) {
                        setPressed(false);
                    }
                    removeTapCallback();
                    removeLongPressCallback();
                    mInContextButtonPress = false;
                    mHasPerformedLongPress = false;
                    mIgnoreNextUpEvent = false;
                    mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
                    break;

                case MotionEvent.ACTION_MOVE:
                    if (clickable) {
                        drawableHotspotChanged(x, y);
                    }

                    final int motionClassification = event.getClassification();
                    final boolean ambiguousGesture =
                            motionClassification == MotionEvent.CLASSIFICATION_AMBIGUOUS_GESTURE;
                    int touchSlop = mTouchSlop;
                    if (ambiguousGesture && hasPendingLongPressCallback()) {
                        if (!pointInView(x, y, touchSlop)) {
                            // The default action here is to cancel long press. But instead, we
                            // just extend the timeout here, in case the classification
                            // stays ambiguous.
                            removeLongPressCallback();
                            long delay = (long) (ViewConfiguration.getLongPressTimeout()
                                    * mAmbiguousGestureMultiplier);
                            // Subtract the time already spent
                            delay -= event.getEventTime() - event.getDownTime();
                            checkForLongClick(
                                    delay,
                                    x,
                                    y,
                                    TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__LONG_PRESS);
                        }
                        touchSlop *= mAmbiguousGestureMultiplier;
                    }

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

                    final boolean deepPress =
                            motionClassification == MotionEvent.CLASSIFICATION_DEEP_PRESS;
                    if (deepPress && hasPendingLongPressCallback()) {
                        // process the long click action immediately
                        removeLongPressCallback();
                        checkForLongClick(
                                0 /* send immediately */,
                                x,
                                y,
                                TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__DEEP_PRESS);
                    }

                    break;
            }

            return true;
        }

        return false;
    }

当事件类型为ACTION_UP的时候就会创建一个PerformClick实例对象,并调用performClickInternal方法通过click点击方式来消费该事件,

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

这里就会我们平时通过setOnClickListener点击事件,然后重写onClick方法方式去消费对应的点击事件,上面是TouchTarget为null且child为null的情况,如果childCount不为0的时候,在按下的时候会从前到后一次遍历每个view,同时获取对应的TouchTarget,

private TouchTarget getTouchTarget(@NonNull View child) {
        for (TouchTarget target = mFirstTouchTarget; target != null; target = target.next) {
            if (target.child == child) {
                return target;
            }
        }
        return null;
    }

如果转换得到的view有对应的事件要处理,会添加绑定对应的TouchTarget,

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

这样子一直到事件被消费处理掉。

总结:
1、View只有事件分发(dispatchTouchEvent)和事件处理(onTouchEvent),ViewGroup有事件分发(dispatchTouchEvent)、事件拦截(onInterceptTouchEvent)、事件处理(onTouchEvent)
2、正常事件流程:dispatchTouchEvent(事件分发)--->onInterceptTouchEvent(事件拦截)->onTouchEvent(事件处理)--->OnTouchListener(事件触摸)--->onClick(事件点击),这里说的正常流程都是系统返回的默认值
3、onInterceptTouchEvent返回值为true,事件会被拦截掉,后面的流程都会被终止掉
4、OnTouchListener返回true,代表事件被消费掉,onClick不会被执行

你可能感兴趣的:(Android事件分发、事件拦截、事件处理分析)