欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Android View事件分发机制 (一)

程序员文章站 2022-05-14 15:27:21
...

当一个点击事件发生时,事件的传递顺序是从Activity -> PhoneWindow -> DecorView(当前界面的容器,setContentView最终得到的布局就是添加到DecorView),然后事件就传递给setContentView这个布局设置的View树上。事件传递的入口是从Activity dispatchTouchEvent 开始处理。

    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            onUserInteraction();
        }
        //将事件传递到window上,然后再到DecorView
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

这里就不去追踪上面的代码的执行过程了,可以查看下PhoneWindow的superDispatchTouchEvent 方法。
接下来我们了解下Activity ViewGroup 和 View 这三者之间的事件分发处理的逻辑。接下来就引出了众所周知的三个核心方法

1、 public boolean dispatchTouchEvent(MotionEvent ev) {}
2、 public boolean onInterceptTouchEvent(MotionEvent ev) {}
3、 public boolean onTouchEvent(MotionEvent event) {}

Activity 和View 只有dispatchTouchEvent 和 onTouchEvent 方法而ViewGroup有这个三个方法。
接下来我们通过日志和操纵dispatchTouchEvent 、onInterceptTouchEvent、onTouchEvent 来观察下事件到底是如何传递的。

public class EventDeliverActivity extends Activity {

    private static final String TAG = "EventDeliverActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_event_deliver);

        /*
        //情况四 案例
        findViewById(R.id.view_1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "onClick: view_1");
            }
        });

        findViewById(R.id.view_1).setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                Log.d(TAG, "onLongClick: view_1");
                return false;
            }
        });

        findViewById(R.id.view_1).setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                Log.d(TAG, "onTouch: view_1");
                return false;
            }
        });
        */
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        int action = ev.getAction();
        switch (action){
            case MotionEvent.ACTION_DOWN:
                Log.d(TAG, " dispatchTouchEvent: ACTION_DOWN");
                break;
            case MotionEvent.ACTION_MOVE:
                Log.d(TAG, " dispatchTouchEvent: ACTION_MOVE");
                break;
            case MotionEvent.ACTION_UP:
                Log.d(TAG, " dispatchTouchEvent: ACTION_UP");
                break;
        }
        return super.dispatchTouchEvent(ev);
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int action = event.getAction();
        switch (action){
            case MotionEvent.ACTION_DOWN:
                Log.d(TAG, " onTouchEvent: ACTION_DOWN");
                break;
            case MotionEvent.ACTION_MOVE:
                Log.d(TAG, " onTouchEvent: ACTION_MOVE");
                break;
            case MotionEvent.ACTION_UP:
                Log.d(TAG, " onTouchEvent: ACTION_UP");
                break;
        }
        return super.onTouchEvent(event);
    }
}
public class ViewGroup_1 extends FrameLayout {

    private static final String TAG = "ViewGroup-1";

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        int action = ev.getAction();
        switch (action){
            case MotionEvent.ACTION_DOWN:
                Log.d(TAG, " dispatchTouchEvent: ACTION_DOWN");
                break;
            case MotionEvent.ACTION_MOVE:
                Log.d(TAG, " dispatchTouchEvent: ACTION_MOVE");
                break;
            case MotionEvent.ACTION_UP:
                Log.d(TAG, " dispatchTouchEvent: ACTION_UP");
                break;
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        int action = ev.getAction();
        switch (action){
            case MotionEvent.ACTION_DOWN:
                Log.d(TAG, " onInterceptTouchEvent: ACTION_DOWN");
                break;
            case MotionEvent.ACTION_MOVE:
                Log.d(TAG, " onInterceptTouchEvent: ACTION_MOVE");
                break;
            case MotionEvent.ACTION_UP:
                Log.d(TAG, " onInterceptTouchEvent: ACTION_UP");
                break;
        }
        return super.onInterceptTouchEvent(ev);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int action = event.getAction();
        switch (action){
            case MotionEvent.ACTION_DOWN:
                Log.d(TAG, " onTouchEvent: ACTION_DOWN");
                break;
            case MotionEvent.ACTION_MOVE:
                Log.d(TAG, " onTouchEvent: ACTION_MOVE");
                break;
            case MotionEvent.ACTION_UP:
                Log.d(TAG, " onTouchEvent: ACTION_UP");
                break;
        }
        return super.onTouchEvent(event);
    }
}
public class View_1 extends TextView {

    private static final String TAG = "View_1";

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        int action = event.getAction();
        switch (action){
            case MotionEvent.ACTION_DOWN:
                Log.d(TAG, " dispatchTouchEvent: ACTION_DOWN");
                break;
            case MotionEvent.ACTION_MOVE:
                Log.d(TAG, " dispatchTouchEvent: ACTION_MOVE");
                break;
            case MotionEvent.ACTION_UP:
                Log.d(TAG, " dispatchTouchEvent: ACTION_UP");
                break;
        }
        return super.dispatchTouchEvent(event);
        //return true;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int action = event.getAction();
        switch (action){
            case MotionEvent.ACTION_DOWN:
                Log.d(TAG, " onTouchEvent: ACTION_DOWN");
                break;
            case MotionEvent.ACTION_MOVE:
                Log.d(TAG, " onTouchEvent: ACTION_MOVE");
                break;
            case MotionEvent.ACTION_UP:
                Log.d(TAG, " onTouchEvent: ACTION_UP");
                break;
        }
        return super.onTouchEvent(event);
        //return true;
    }
}

为了节约篇幅删除了一些构造方法。下面我们通过控制三个核心方法,是否分发、是否中断、是否处理来观察事件的执行过程。

情况一 Activity -> ViewGroup_1 -> View_1 所有的事件方法都不做任何处理

事件传递顺序是:

 DOWN事件:
         EventDeliverActivity:  dispatchTouchEvent: ACTION_DOWN
         ViewGroup-1:  dispatchTouchEvent: ACTION_DOWN
         ViewGroup-1:  onInterceptTouchEvent: ACTION_DOWN
         View_1:  dispatchTouchEvent: ACTION_DOWN
         View_1:  onTouchEvent: ACTION_DOWN
         ViewGroup-1:  onTouchEvent: ACTION_DOWN
         EventDeliverActivity:  onTouchEvent: ACTION_DOWN
MOVE事件:
         EventDeliverActivity:  dispatchTouchEvent: ACTION_MOVE
         EventDeliverActivity:  onTouchEvent: ACTION_MOVE
         EventDeliverActivity:  dispatchTouchEvent: ACTION_MOVE
         EventDeliverActivity:  onTouchEvent: ACTION_MOVE
UP事件:
         EventDeliverActivity:  dispatchTouchEvent: ACTION_UP
         EventDeliverActivity:  onTouchEvent: ACTION_UP

综上得出结论: 事件传递的过程是 先dispatchTouchEvent -> onInterceptTouchEvent -> onTouchEvent并且dispatchTouchEventonInterceptTouchEvent在同一级调用就是说Activity 调用完了dispatchTouchEvent,会调用DecorViewdispatchTouchEventonInterceptTouchEvent方法,接着调用ViewGroup-1的dispatchTouchEventonInterceptTouchEvent方法 ,然后调用View_1的dispatchTouchEvent方法,接着在从onTouchEvent依次往上开始回调父View的onTouchEvent

情况二 Activity -> ViewGroup_1 -> View_1 在View_1的dispatchTouchEvent 或者 onTouchEvent 返回true

对View_1 的 dispatchTouchEvent return true

一、对View_1 的 dispatchTouchEvent return true

DOWN事件:
         EventDeliverActivity:  dispatchTouchEvent: ACTION_DOWN
         ViewGroup-1:  dispatchTouchEvent: ACTION_DOWN
         ViewGroup-1:  onInterceptTouchEvent: ACTION_DOWN
         View_1:  dispatchTouchEvent: ACTION_DOWN
MOVE事件:
         EventDeliverActivity:  dispatchTouchEvent: ACTION_MOVE
         ViewGroup-1:  dispatchTouchEvent: ACTION_MOVE
         ViewGroup-1:  onInterceptTouchEvent: ACTION_MOVE
         View_1:  dispatchTouchEvent: ACTION_MOVE
UP事件:
         EventDeliverActivity:  dispatchTouchEvent: ACTION_UP
         ViewGroup-1:  dispatchTouchEvent: ACTION_UP
         ViewGroup-1:  onInterceptTouchEvent: ACTION_UP
         View_1:  dispatchTouchEvent: ACTION_UP
         
二、对View_1 的 onTouchEvent return true

DOWN事件:
         EventDeliverActivity:  dispatchTouchEvent: ACTION_DOWN
         ViewGroup-1:  dispatchTouchEvent: ACTION_DOWN
         ViewGroup-1:  onInterceptTouchEvent: ACTION_DOWN
         View_1:  dispatchTouchEvent: ACTION_DOWN
         View_1:  onTouchEvent: ACTION_DOWN
MOVE事件:
         EventDeliverActivity:  dispatchTouchEvent: ACTION_MOVE
         ViewGroup-1:  dispatchTouchEvent: ACTION_MOVE
         ViewGroup-1:  onInterceptTouchEvent: ACTION_MOVE
         View_1:  dispatchTouchEvent: ACTION_MOVE
         View_1:  onTouchEvent: ACTION_MOVE
UP事件:
         EventDeliverActivity:  dispatchTouchEvent: ACTION_UP
         ViewGroup-1:  dispatchTouchEvent: ACTION_UP
         ViewGroup-1:  onInterceptTouchEvent: ACTION_UP
         View_1:  dispatchTouchEvent: ACTION_UP
         View_1:  onTouchEvent: ACTION_UP

综上得出结论: dispatchTouchEvent 或者 onTouchEvent 返回true 将会直接导致事件被终止,如何终止? 如DOWN事件它会不继续往下传递,而是走MOVE和UP事件。调用顺序是Activity 的dispatchTouchEvent DOWN事件 然后会调用DecorViewdispatchTouchEventonInterceptTouchEvent方法接着会调用ViewGroup_1的 dispatchTouchEventonInterceptTouchEvent方法的DOWN事件,然后调用View_1的dispatchTouchEvent DOWN事件, 然后DOWN事件就终止了,继续MOVE和UP时间。对于ViewGroup_1 也是同样的道理这里就不举例了。

情况三 Activity -> ViewGroup_1 -> View_1 在ViewGroup_1的onInterceptTouchEvent 返回true

DOWN事件:
         EventDeliverActivity:  dispatchTouchEvent: ACTION_DOWN
         ViewGroup-1:  dispatchTouchEvent: ACTION_DOWN
         ViewGroup-1:  onInterceptTouchEvent: ACTION_DOWN
         ViewGroup-1:  onTouchEvent: ACTION_DOWN
         EventDeliverActivity:  onTouchEvent: ACTION_DOWN
MOVE事件:
         EventDeliverActivity:  dispatchTouchEvent: ACTION_MOVE
         EventDeliverActivity:  onTouchEvent: ACTION_MOVE
UP事件:
         EventDeliverActivity:  dispatchTouchEvent: ACTION_UP
         EventDeliverActivity:  onTouchEvent: ACTION_UP

综上得出结论,如果在ViewGroup_1的onInterceptTouchEvent 返回true 它会导致事件不在向下传,而是直接给它自己的onTouchEvent处理,然后根据onTouchEvent返回情况,在调用自己的父View的onTouchEvent。 简单说就是改变了事件的传递方向。 好比一个球从十楼开始*落体,dispatchTouchEvent 向下走,onInterceptTouchEvent是决定是否要反弹,onTouchEvent是向上走。 现在在中间楼层的onInterceptTouchEvent 返回true, 那么球就从中间楼层开始反弹了,而不是一直掉到一楼才开始反弹向上走。

情况四 看看View_1 onTouch onClick 以及 onLongClick方法的调用时机

DOWN事件:
         EventDeliverActivity:  dispatchTouchEvent: ACTION_DOWN
         ViewGroup-1:  dispatchTouchEvent: ACTION_DOWN
         ViewGroup-1:  onInterceptTouchEvent: ACTION_DOWN
         View_1:  dispatchTouchEvent: ACTION_DOWN
         EventDeliverActivity: onTouch: view_1
         View_1:  onTouchEvent: ACTION_DOWN
MOVE事件:
         EventDeliverActivity:  dispatchTouchEvent: ACTION_MOVE
         ViewGroup-1:  dispatchTouchEvent: ACTION_MOVE
         ViewGroup-1:  onInterceptTouchEvent: ACTION_MOVE
         View_1:  dispatchTouchEvent: ACTION_MOVE
         EventDeliverActivity: onTouch: view_1
         View_1:  onTouchEvent: ACTION_MOVE
UP事件:
         EventDeliverActivity:  dispatchTouchEvent: ACTION_UP
         ViewGroup-1:  dispatchTouchEvent: ACTION_UP
         ViewGroup-1:  onInterceptTouchEvent: ACTION_UP
         View_1:  dispatchTouchEvent: ACTION_UP
         EventDeliverActivity: onTouch: view_1
         View_1:  onTouchEvent: ACTION_UP
         EventDeliverActivity: onClick: view_1

综上上面的打印日志分析得出, view_1的onClick事件发生在UP事件以后响应,并且在View_1的onTouchEvent 中响应。view_1 的 onTouch 方法发生在 dispatchTouchEventonTouchEvent 之间。

结合源码查看验证,分别在View.java 的 public boolean dispatchTouchEvent(MotionEvent event) {}方法中,可以看到先是调用 li.mOnTouchListener.onTouch(this, event)方法, 如果返回true的话,就会得到result=true if (!result && onTouchEvent(event)) {} 就可以得出 onTouchEvent 不会被执行。如果返回false onTouchEvent方法被执行,接着在ACTION_UP事件处理时,performClickInternal() -> performClick()调用
调用onClick方法在onTouchEvent ACTION_DOWN 事件中 checkForLongClick(0, x, y); 触发longClick事件。

    public boolean dispatchTouchEvent(MotionEvent event) {
        boolean result = false;
        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)) {
                    //onTouch方法的返回值讲直接决定了onTouchEvent是否被调用,如果返回true 代表事件被消费处理
               
                result = true;
            }
			// onTouchEvent 处理onClick和onLongClick事件
            if (!result && onTouchEvent(event)) {
                result = true;
            }
        }
        return result;
    }
    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.
                                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(0, x, y);
                        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(0, x, y);
                    }
                    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);
                    }

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

            return true;
        }

        return false;
    }

最后通过一张图表示上面的几次实验的结果。
Android View事件分发机制 (一)

相关标签: 事件分发