Android自定义View(二)View的事件分发机制

本文详细解析了Android中View的事件分发机制,包括Activity到View的传递顺序,重点分析了ViewGroup和View的dispatchTouchEvent方法。讨论了如何在自定义View中拦截和处理事件,以及解决滑动冲突的策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

View的事件分发机制是Android中的一个难点,也是非常重要的知识点,充分理解和掌握事件分发机制有助于我们在自定义View的时候更好地分析和解决问题

整体上来看,View事件的大致传递顺序是Activity->Window->ViewGroup->View,首先到activity的dispatchTouchEvent,然后到Activity内部的Window,Window再传递给DecorView,由DecorView再到顶级View,顶级View是我们在Activity中用setContentView设置的View,一般是一个ViewGroup,ViewGroup又会把事件分发给它的子view,当然子view可以是ViewGroup也可以是View

dispatchTouchEvent是可以说是所有事件分发的入口函数,其中ViewGroup和View都有dispatchTouchEvent方法,但是它们对事件的处理逻辑是完全不一样的,这里先从ViewGroup的dispatchTouchEvent方法开始分析

ViewGroup的dispatchTouchEvent方法,源码如下:

public boolean dispatchTouchEvent(MotionEvent ev) {
        // 省略部分代码..............

        // Check for interception. 
        // mFirstTouchTarget 代表是否有子view消费了事件
        final boolean intercepted; //是否拦截事件
        //在允许拦截事件的情况下,view的down事件都会调用onInterceptTouchEvent方法,询问是否
        //需要拦截事件,还有就是有子view消费事件的时候,也会调用onInterceptTouchEvent方法
        //如果没有子view消费事件,代表没必要分发事件了,直接intercepted为true拦截事件
        if (actionMasked == MotionEvent.ACTION_DOWN
                || mFirstTouchTarget != null) {
            //是否允许拦截事件,可以自己设置
            final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
            if (!disallowIntercept) { //允许拦截
                //调用了拦截事件的方法,返回Boolean代表是否拦截事件,ViewGroup一般默认不拦截事件,返回false,
                //可以重写此方法返回true代表拦截,然后事件将不再往下分发  
                intercepted = onInterceptTouchEvent(ev); 
                ev.setAction(action); // restore action in case it was changed
            } else {
                intercepted = false;
            }
        } else {
            // 意思就是当前事件不是down事件并且没有子view消费,所有此viewgroup直接拦截事件
            // 也可以这么理解,一开始down事件分发下去,然而下一级view并没有消费事件,那么
            // 此后的其他事件如move、up都不再分发给下一级了
            // There are no touch targets and this action is not an initial down
            // so this view group continues to intercept touches.
            intercepted = true;
        }
        
         //如果事件没有取消并且viewgroup不拦截事件,则执行事件的分发
         if (!canceled && !intercepted) {
               // 省略部分代码...................           

               //循环遍历ViewGroup的子view,逐一询问子view是否消费事件
                final int childrenCount = mChildrenCount; //子view个数
                // 
                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,从最后添加的子view开始,代表先分发给后添加的子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;
                        }

                        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);
                         //方法dispatchTransformedTouchEvent是将事件分发给当前child,返回值代表child是否消费了事件,
                         //如果为true代表子view消费了事件,此时将跳出循环结束事件的分发,如果为false,代表子view没有消费事件,那么将继续分发给下一个子view
                        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();
                            //因为有子view消费了事件,所以给newTouchTarget 赋值 
                            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.
        //没有子view消费事件或viewgroup直接拦截事件
        if (mFirstTouchTarget == null) { //当viewgroup拦截事件的时候也会执行这里
            // dispatchTransformedTouchEvent中会调用viewgroup父类即View的dispatchTouchEvent方法,代表由ViewGroup自身消费此事件
            // 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;
                //如果事件已经传递并且被当前子view消费的,那么就handled为true,那么当前方法就返回true
                if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
                    handled = true;
                } else { //处理事件被cancel的情况
                    
                    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的dispatchTouchEvent方法中,首先通过onInterceptTouchEvent方法的返回值来询问是否需要拦截事件,如果要拦截事件,则事件就由当前ViewGroup消费而不再往下分发,如果不拦截事件,则分发给下面的子view

在源码中可以看到,ViewGroup通过循环遍历它的所有子view,逐一询问子view是否消费此事件,如果子view消费了事件,则返回true,跳出循环,当子view不消费事件则返回false,继续遍历询问下一个子view,如果所有的子view都不消费事件,则会调用viewgroup父类即view的onTouchEvent方法,代表viewgroup自己消费此事件,通过dispatchTransformedTouchEvent方法来实现

dispatchTransformedTouchEvent源码如下:

 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) {
                // 当viewgroup的所有子view都不消费事件的时候,参数child就为null
                handled = super.dispatchTouchEvent(event);
            } else {
                handled = child.dispatchTouchEvent(event);
            }
            event.setAction(oldAction);
            return handled;
        }

当ViewGroup的遍历子view完成以后,如果没有子view消费事件或者当前ViewGroup根本就没有子view,那么下面的mFristTouchTarget将等于null,在dispatchTransformedTouchEvent方法中的参数child将传null值,然后调用super.dispatchTouchEvent方法,此时事件就由ViewGroup自己消费

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

       //省略代码..................

        }

 

上面分析完了ViewGroup的dispatchTouchEvent方法,这是一个ViewGroup的事件分发流程图:

 

分析了ViewGroup的事件分发,接下来我们分析View的dispatchTouchEvent方法,因为View是ViewGroup的父类,所以View的dispatchTouchEvent既代表了View的事件处理机制,也代表了在某些情况下ViewGroup的事件处理机制;

以我的总结,View的这个方法在以下三种情况会被调用,一是ViewGroup分发事件但是没有子view消费事件,二是ViewGroup本来就没有子view,三是控件是View而不是ViewGroup;代码如下:

//view的处理事件的方法
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;
            }
            //如果设置mOnTouchListener监听,优先将事件交给onTouch方法处理
            //noinspection SimplifiableIfStatement
            ListenerInfo li = mListenerInfo;
            if (li != null && li.mOnTouchListener != null
                    && (mViewFlags & ENABLED_MASK) == ENABLED
                    && li.mOnTouchListener.onTouch(this, event)) {
                result = true;
            }

            //如果没有设置onTouch方法,则将事件交给onTouchEvent方法处理,可见onTouch方法的优先级是最高的
            if (!result && onTouchEvent(event)) {
                // 看onTouchEvent是否消费事件
                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;
    }

如果View设置了onTouchListener监听,会优先将事件先交由onTouch方法处理,如果没有或者onTouch返回false,则交给onTouchEvent处理,看看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;

        //省略代码。。。。。。。。。。。。。。。。。
        // 若view可点击或者可长按以及长按出现ToolTip
        // 8.0新加的TOOLTIP,解释当前的View是干什么的,可以在View中设置    android:tooltipText=""设置,长按View会出现提示""设置的提示信息,所以这里和clickable平级“或”的关系
        if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
            switch (action) {
                // 在ACTION_UP的时候会执行点击事件
                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.
                                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;
                
            //省略代码。。。。。。。。。。。。。。。。 

      
            }
            // 代表消费了事件
            return true;
        }
        // 返回false代表不消费事件
        return false;
    }

分析一下点击事件是如何响应的,首先判断当前View是否为可点击的,一般来说ViewGroup默认是不可点击的,所以一般ViewGroup的onTouchEvent方法返回false,所以ViewGroup一般默认是不消费事件的,如果是可点击则执行performClick方法,onTouchEvent就会返回true,所以对于view来说,只要它是可点击或者可长按的,都会消费事件并返回true,比如Button、ImageView、ImageButton等控件都会消费事件

这是一个View的事件分发流程图:

通过上面的总结分析,我们掌握ViewGroup和View的dispatchTouchEvent方法的事件分发机制,总结一下自定义view中关于事件分发的常见需求:

1.如果想在ViewGroup中拦截事件并且不让事件向下分发,可以重写onInterceptTouchEvent方法并返回true,然后事件会交给onTouchEvent方法处理,通过重写onTouchEvent方法来处理事件

2.如果我们需要在ViewGroup中处理事件,但是不拦截事件,那么就重写dispatchTouchEvent方法,在此方法中获取事件

3.处理滑动冲突的时候,可以重写onInterceptTouchEvent方法,根据具体业务逻辑判断是否拦截事件,也可以重写dispatchTouchEvent方法,所有事件先传给子view,如果子view需要就消费,不需要就返回给父容器的onTouchEvent消费

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值