Android事件分发机制

Activity的事件分发

 

  • dispatchTouchEvent
public boolean dispatchTouchEvent(MotionEvent ev) {
    if (ev.getAction() == MotionEvent.ACTION_DOWN) {
        //作用:实现屏保功能,该方法时空方法。当activity位于栈顶时,触屏点击按home、back、menu等会触发此方法
        onUserInteraction();
    }
    if (getWindow().superDispatchTouchEvent(ev)) {
         /**
         * 若 getWindow().superDispatchTouchEvent(ev)的返回true
         * 则Activity.dispatchTouchEvent()就返回 true,则方法结束。即 :该点击事件停止往下传递 & 事件传递过程结束。
        * 否则:继续往下调用 Activity.onTouchEvent
        */
        return true;
    }
    return onTouchEvent(ev);
}
  1. getWindow().superDispatchTouchEvent(ev)
    1. getWindow() = 获取Window类对象
    2. Window类使抽象类,其唯一实现类是PhoneWindow类,此处Window对象 = PhoneWindow类对象。
    3. Window类的superDispatchTouchEvent()方法是抽象方法,由其实现类PhoneWindow类实现。
  2. PhoneWindow.superDispatchTouchEvent()
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
    //mDecor = 顶层 View(DecorView)的实例对象
    return mDecor.superDispatchTouchEvent(event);
}
  1. DecorView.superDispatchTouchEvent()
    1. DecorView 继承自 FrameLayout,是所有界面的父类
    2. DecorView类是PhoneWindow类的一个内部类(API23以后将DecorView拿出来了)。
    3. FrameLayout 是 ViewGroup 的子类,故 DecorView 的间接父类 = ViewGroup
public boolean superDispatchTouchEvent(MotionEvent event) {
    // 调用父类的方法 = ViewGroup 的 dispatchTouchEvent()
    // 即 将事件传递到 ViewGroup 去处理
    return super.dispatchTouchEvent(event);
}
  • onTouchEvent
public boolean onTouchEvent(MotionEvent event) {
    //当一个点击事件未被 Activity 下任何一个 View 接收 / 处理时
    // 应用场景:处理发生在 Window 边界外的触摸事件
    // 即只有在点击事件在 Window 边界外才会返回 true,一般情况都返回 false。
    if (mWindow.shouldCloseOnTouch(this, event)) {
        finish();
        return true;
    }
    return false;
}

ViewGroup事件分发

 

 

  • dispatchTouchEvent
// ViewGroup # dispatchTouchEvent
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        ... ...
        boolean handled = false;
        if (onFilterTouchEventForSecurity(ev)) {
            final int action = ev.getAction();
            final int actionMasked = action & MotionEvent.ACTION_MASK;
            ... ...
            // 记录是否需要拦截事件, intercepted = true表示拦截, intercepted = false表示不拦截
            final boolean intercepted;
            if (actionMasked == MotionEvent.ACTION_DOWN
                    || mFirstTouchTarget != null) {
                //disallowIntercept为是否开启禁止拦截的标志,当disallowIntercept=true时禁止拦截,否则开启
                //调用requestDisallowInterceptTouchEvent(boolean disallowIntercept)方法可以设置是否关闭拦截 
                final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
                if (!disallowIntercept) {
                    //执行onInterceptTouchEvent方法,也就是我们自己定义的回调
                    //默认onInterceptTouchEvent(ev)方法返回false,不拦截事件,当返回true时表示事件拦截
                    intercepted = onInterceptTouchEvent(ev);
                    ev.setAction(action); // restore action in case it was changed
                } else {
                    intercepted = false;
                }
            } else {
                //当没有触摸targets,且不是down时间时,开始持续拦截触摸。
                intercepted = true;
            }
            ... ...
            // Check for cancelation.
            final boolean canceled = resetCancelNextUpFlag(this)
                    || actionMasked == MotionEvent.ACTION_CANCEL;
            ... ...
            //没有取消并且没有拦截事件时进入判断
            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) {
                            ... ...
                            for (int i = childrenCount - 1; i >= 0; i--) {
                            //判断子View是否获取用户焦点,如果未获取则直接跳过本次循环
                            if (childWithAccessibilityFocus != null) {
                                if (childWithAccessibilityFocus != child) {
                                    continue;
                                }
                                childWithAccessibilityFocus = null;
                                i = childrenCount - 1;
                            }
                            //判断触摸点是不是在子View范围内或者子View不可见,如果不在则直接跳过本次循环
                            if (!canViewReceivePointerEvents(child)
                                    || !isTransformedTouchPointInView(x, y, child, null)) {
                                ev.setTargetAccessibilityFocus(false);
                                continue;
                            }
                            ... ...
                            //触摸点在子View范围内,则调用dispatchTransformedTouchEvent()将事件分发给ViewGroup或View
                            if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
                                // Child wants to receive touch within its bounds.
                                ... ...
                                mLastTouchDownX = ev.getX();
                                mLastTouchDownY = ev.getY();
                                //将找到的View加入到TouchTarget当中
                                newTouchTarget = addTouchTarget(child, idBitsToAssign);
                                alreadyDispatchedToNewTouchTarget = true;
                                //找到View 跳出循环
                                break;
                            }
                            ... ...
                        }
                    }
                    ... ...
                }
            }

            // 当没有View消费事件,即mFirstTouchTarget = null
            //ViewGroup自己消费
            if (mFirstTouchTarget == null) {
                // 这里调用dispatchTransformedTouchEvent,其实也就是调用ViewGroup自身TouchEvent事件
                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;
    }

注:

标记位FLAG_DISALLOW_INTERCEPT

mGroupFlags可以通过requestDisallowInterceptTouchEvent设置

requestDisallowInterceptTouchEvent:设置是否禁用拦截

@Override
    public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
        if (disallowIntercept == ((mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0)) {
            // We're already in this state, assume our ancestors are too
            return;
        }

        if (disallowIntercept) {
            mGroupFlags |= FLAG_DISALLOW_INTERCEPT;
        } else {
            mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;
        }

        // Pass it up to our parent
        if (mParent != null) {
            mParent.requestDisallowInterceptTouchEvent(disallowIntercept);
        }
    }

注:在处理子View与ViewGroup滑动冲突的时候,我们可以在子View中调用父View的requestDisallowInterceptTouchEvent()方法,阻止父View拦截事件。

dispatchTransformedTouchEvent:

 private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
            View child, int desiredPointerIdBits) {
        final boolean handled;
        ... ...
        // Perform any necessary transformations and dispatch.
        if (child == null) {
            handled = super.dispatchTouchEvent(transformedEvent);
        } else {
            ... ...
            handled = child.dispatchTouchEvent(transformedEvent);
        }
        // Done.
        transformedEvent.recycle();
        return handled;
    }

注:用来处理调用ViewGroup(super.dispatchTouchEvent ->View.dispatchTouchEvent ->View.onTouchEvent还是调用ViewGroup里面的子View(View.onTouchEvent)

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

注:ViewGroup默认是不进行拦截,在ViewGroup子类中重写这个方法,并在内部实现是否拦截逻辑。

  • onTouchEvent(父类View.onTouchEvent)

注:通过dispatchTransformedTouchEvent决定是分发事件还是调用自己父类的onTouchEvent

View事件分发

 

 

  • dispatchTouchEvent
//返回结果定义在方法内部变量result当中,当result返回true时,表示事件被消费,不再继续向下分发,为false时继续向下分发
 public boolean dispatchTouchEvent(MotionEvent event) {
    ...
    //判断窗口window是否被遮挡,方法返回为true,事件可以被继续分发,false不再继续分发
    if (onFilterTouchEventForSecurity(event)) {
        //View当前是否被激活,并且有滚动事件发生
        if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
            result = true;
        }
        //ListenerInfo是一个内部类,定义了一些监听事件(onClickLinstener, onTouchListener等等)
        ListenerInfo li = mListenerInfo;
        //li != nul:
        //li.mOnTouchListener != null:这个li.mOnTouchListener变量就是通过setOnTouchEvent赋值的。
        //(mViewFlags & ENABLED_MASK) == ENABLED:当前View是被激活的状态
        //li.mOnTouchListener.onTouch(this, event):在我们setOnTouchEvent内部有操作,当在这里我们设置View的TouchEvent事件,当返回为true时,reslult=true表示消耗这个事件,将不再继续往下传递。
        if (li != null && li.mOnTouchListener != null
                && (mViewFlags & ENABLED_MASK) == ENABLED
                && li.mOnTouchListener.onTouch(this, event)) {
            result = true;
        }

        //onTouchEvent(event)也返回true时,result=true
        if (!result && onTouchEvent(event)) {
            result = true;
        }
    }
    ...
    return result;
}

注:View会先判断自己是否有设置OnTouchListener,如果所设置的OnTouchListener得onTouch返回true,则直接消耗点击事件,不再执行onTouchEvent()方法。

OnTouchListener在setOnTouchListener()中赋值。

OnTouchListener的onTouch方法需要手动复写,例如复写Button.setOnTouchListener()方法

button.setOnTouchListener(new OnTouchListener() {  
        @Override  
        public boolean onTouch(View v, MotionEvent event) {  
            ...
            return false;  
        }  
});
  • onTouchEvent
public boolean onTouchEvent(MotionEvent event) {
    ...
    //当前视图是否可被执行点击、长按等操作
    //可通过java代码或者xml代码设置enable状态或者clickable状态。
    //当这些状态为false时,则clickable = false,否则为true。
    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;
        //一个已经销毁的视图,被点击时依旧消费事件,只是不能响应事件
        return clickable;
    }
    if (mTouchDelegate != null) {
        if (mTouchDelegate.onTouchEvent(event)) {
            return true;
        }
    }

    if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
        switch (action) {
            case MotionEvent.ACTION_UP:
                ...
                 //判断是否可点击
                if (!clickable) {
                    removeTapCallback();
                    removeLongPressCallback();
                    mInContextButtonPress = false;
                    mHasPerformedLongPress = false;
                    mIgnoreNextUpEvent = false;
                    break;
                }
                boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
                if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
                    // 判断是否可以获取焦点,如果可以,则获取焦点
                    boolean focusTaken = false;
                    if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
                        focusTaken = requestFocus();
                    }

                    if (prepressed) {
                        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) {
                            if (mPerformClick == null) {
                                mPerformClick = new PerformClick();
                            }
                            //最终ACTION_UP要执行的方法,post到UI Thread的中的一个Runnable,如果不存在message queue,则直接执行performClick();
                            if (!post(mPerformClick)) {
                                performClick();
                            }
                        }
                    }
                    ...
                }
                break;
            case MotionEvent.ACTION_DOWN:
                ...
                break;
            case MotionEvent.ACTION_CANCEL:
                ...
                break;
            case MotionEvent.ACTION_MOVE:
                ...
                break;
        }
        return true;
    }
    return false;
}

注:clickable在View包括继承自View的自定义View当中默认是fasle的,但是在Button、TextView当中默认就是true。当我们设置了setOnClickListener时会也会执行clickable=true。

performClick():

public boolean performClick() {
    final boolean result;
    final ListenerInfo li = mListenerInfo;
    if (li != null && li.mOnClickListener != null) {
        playSoundEffect(SoundEffectConstants.CLICK);
        //这里实际上就是调用了我们的setOnClickListerner.onClick()方法
        li.mOnClickListener.onClick(this);
        result = true;
    } else {
        result = false;
    }
    sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
    return result;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值