Android中onInterceptTouchEvent、dispatchTouchEvent及onTouchEvent的调用顺序及内部原理

来源:互联网 发布:怎样做网络推广赚钱 编辑:程序博客网 时间:2024/06/08 00:46

在Android中需要经常对用户手势进行判断,在判断手势时需要精细的分清楚每个触摸事件以及每个View对事件的接收情况,在View,ViewGroup,Activity中都可以接收事件,在对事件进行处理时onInterceptTouchEvent、dispatchTouchEvent及onTouchEvent这三个函数的调用顺序及关系需要好好理清楚。原理代码有点多,如果不对着具体事例,理解起来很难。下面对着代码进行分析。代码地址为:https://github.com/huangtianyu/DispatchTouchEvent,记得帮忙点Star

MainActivity.java

package com.zqc.dispatchtouchevent;import android.app.Activity;import android.os.Bundle;import android.util.Log;import android.view.MotionEvent;import android.view.View;import static com.zqc.dispatchtouchevent.Constants.TAG;public class MainActivity extends Activity implements View.OnTouchListener {    private MyView myView;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        Log.e(TAG, "MainActivity onCreate");        setContentView(R.layout.activity_main);        myView = (MyView) findViewById(R.id.myview);        myView.setOnTouchListener(MainActivity.this);    }    @Override    public boolean dispatchTouchEvent(MotionEvent ev) {        Log.e(TAG, "MainActivity dispatchTouchEvent");        return super.dispatchTouchEvent(ev);    }    @Override    public boolean onTouchEvent(MotionEvent event) {        Log.e(TAG, "MainActivity onTouchEvent");        switch (event.getAction()) {            case MotionEvent.ACTION_DOWN:                Log.e(TAG, "MainActivity onTouchEvent ACTION_DOWN");                break;            case MotionEvent.ACTION_MOVE:                Log.e(TAG, "MainActivity onTouchEvent ACTION_MOVE");                break;            case MotionEvent.ACTION_CANCEL:                Log.e(TAG, "MainActivity onTouchEvent ACTION_CANCEL");                break;            case MotionEvent.ACTION_UP:                Log.e(TAG, "MainActivity onTouchEvent ACTION_UP");                break;            default:                Log.e(TAG, "MainActivity onTouchEvent " + event.getAction());                break;        }        return super.onTouchEvent(event);    }    @Override    protected void onResume() {        Log.e(TAG, "MainActivity onResume");        super.onResume();    }    @Override    protected void onPause() {        Log.e(TAG, "MainActivity onPause");        super.onPause();    }    @Override    public boolean onTouch(View v, MotionEvent event) {        Log.e(TAG, "MainActivity onTouch");        switch (event.getAction() & MotionEvent.ACTION_MASK) {            case MotionEvent.ACTION_DOWN:                Log.e(TAG, "MainActivity onTouch ACTION_DOWN");                break;            case MotionEvent.ACTION_MOVE:                Log.e(TAG, "MainActivity onTouch ACTION_MOVE");                break;            case MotionEvent.ACTION_CANCEL:                Log.e(TAG, "MainActivity onTouch ACTION_CANCEL");                break;            case MotionEvent.ACTION_UP:                Log.e(TAG, "MainActivity onTouch ACTION_UP");                break;            default:                Log.e(TAG, "MainActivity onTouchEvent " + event.getAction());                break;        }        return false;    }}
MyView.java

package com.zqc.dispatchtouchevent;import android.content.Context;import android.util.AttributeSet;import android.util.Log;import android.view.GestureDetector;import android.view.MotionEvent;import android.widget.TextView;import static com.zqc.dispatchtouchevent.Constants.MY_GESTURE_TAG;import static com.zqc.dispatchtouchevent.Constants.TAG;public class MyView extends TextView {    private Context mContext;    //private GestureDetector mGesture;    public MyView(Context context) {        this(context, null);    }    public MyView(Context context, AttributeSet attrs) {        super(context, attrs);        Log.e(TAG, "MyView");        mContext = context;        //手势初始化       // mGesture = new GestureDetector(mContext, mGestureListener);    }    @Override    public boolean onTouchEvent(MotionEvent event) {        Log.e(TAG, "MyView onTouchEvent");        switch (event.getAction()) {            case MotionEvent.ACTION_DOWN:                Log.e(TAG, "MyView onTouchEvent ACTION_DOWN");                break;            case MotionEvent.ACTION_MOVE:                Log.e(TAG, "MyView onTouchEvent ACTION_MOVE");                break;            case MotionEvent.ACTION_CANCEL:                Log.e(TAG, "MyView onTouchEvent ACTION_CANCEL");                break;            case MotionEvent.ACTION_UP:                Log.e(TAG, "MyView onTouchEvent ACTION_UP");                break;            default:                Log.e(TAG, "MyView onTouchEvent " + event.getAction());                break;        }//        设置手势监听       // mGesture.onTouchEvent(event);        return super.onTouchEvent(event);    }    @Override    public boolean dispatchTouchEvent(MotionEvent event) {        Log.e(TAG, "MyView dispatchTouchEvent");        return super.dispatchTouchEvent(event);    }}

MyViewGroup.java

package com.zqc.dispatchtouchevent;import android.content.Context;import android.util.AttributeSet;import android.util.Log;import android.view.MotionEvent;import android.widget.RelativeLayout;import static com.zqc.dispatchtouchevent.Constants.TAG;public class MyViewGroup extends RelativeLayout {    public MyViewGroup(Context context) {        this(context, null);    }    public MyViewGroup(Context context, AttributeSet attrs) {        super(context, attrs);        Log.e(TAG, "MyViewGroup");    }    @Override    public boolean onInterceptTouchEvent(MotionEvent ev) {        Log.e(TAG, "MyViewGroup onInterceptTouchEvent");        return super.onInterceptTouchEvent(ev);    }    @Override    public boolean dispatchTouchEvent(MotionEvent ev) {        Log.e(TAG, "MyViewGroup dispatchTouchEvent");        return super.dispatchTouchEvent(ev);    }    @Override    public boolean onTouchEvent(MotionEvent event) {        Log.e(TAG, "MyViewGroup onTouchEvent");        switch (event.getAction()) {            case MotionEvent.ACTION_DOWN:                Log.e(TAG, "MyViewGroup onTouchEvent ACTION_DOWN");                break;            case MotionEvent.ACTION_MOVE:                Log.e(TAG, "MyViewGroup onTouchEvent ACTION_MOVE");                break;            case MotionEvent.ACTION_CANCEL:                Log.e(TAG, "MyViewGroup onTouchEvent ACTION_CANCEL");                break;            case MotionEvent.ACTION_UP:                Log.e(TAG, "MyViewGroup onTouchEvent ACTION_UP");                break;            default:                Log.e(TAG, "MyViewGroup onTouchEvent " + event.getAction());                break;        }        return super.onTouchEvent(event);    }}
Contants.java

package com.zqc.dispatchtouchevent;public class Constants {    public final static String TAG = "MY_LOG";    public final static String MY_GESTURE_TAG = "GESTURE_TAG";}
在代码中将每个函数分别列出并加上Log输出,这样对着Log日志进行分析,则一目了然。

1.让所有的onInterceptTouchEvent、dispatchTouchEvent及onTouchEvent均返回super.onTouchEvent即均返回false时,轻轻点击MyView然后快速抬起,查看相应的Log:


通过Log能清楚的查看代码执行的流程,具体流程如下:

DOWN事件:MainActivity.dispatchTouchEvent->MyViewGroup.dispatchTouchEvet->MyViewGroup.onInterceptTouchEvent->MyView.dispatchTouchEvent->setOnTouchListener.onTouch->MyView.onTouchEvent->MyViewGroup.onTouchEvent->MainActivity.onTouchEvent

UP事件:MainActivity.dispatchTouchEvent->MainActivity.onTouchEvent

从上面流程可以看出,点击事件最先传给窗口Activity的dispatchTouchEvent函数进行事件分发,然后对于View类,是先传给对应的父View的dispatchTouchEvent进行事件分发,然后在传给里面点击的View。当down事件没有被各个view消费时,最终会调用Acitivity的onTouchEvent,并在在Down后续的UP事件不在传给MyViewGroup和MyView,直接传给MainAcitivity。所以当事件没有被窗口中的View消费时,最终都是给了该窗口Activity类中的onTouchEvent事件处理。从Log中也可以看出setOnTouchListener中的onTouch事件是在对应View的onTouchEvent事件之前被执行。

2.当MainAcivity中dispathTouchEvent返回true时,轻轻点击MyView,查看对应Log:


通过Log可以看到当窗口Activity的dispatchTouchEvent返回true时,DOWN事件没有往View中传,也就没有调用任何的onTouchEvent事件,UP事件也是走到Activity的dispatchTouchEvent时也就结束了。

3.重新置Activity中dispatchTouchEvent返回false,然后置ViewGroup中onInterceptTouchEvent返回true时,轻轻点击MyView查看对应Log:


这时DOWN事件和UP事件的执行流程如下:

DOWN事件:MainActivity.dipatchTouchEvent->MyViewGroup.dispatchTouchEvent->MyViewGroup.onInterceptTouchEvent->MyViewGroup.onTouchEvent->MainActivity.onTouchEvent.

UP事件:MainActiviy.dispatchTouchEvent->MainActivity.onTouchEvent.

从Log中可以看出,当onInterceptTouchEvent返回true时,事件即被MyViewGroup拦截了,这时事件就直接传给MyViewGroup.onTouchEvent,不在往子View传,由于MyViewGroup.onTouchEvent返回的是false,即MyViewGroup并没有消费事件,这时事件会传给窗口Activity,UP事件会传给最后一个接受Down事件的窗口或View。

4.当MyView中onTouchEvent返回true时,即MyView会消费传给他的事件。轻点MyView查看对应的Log:


继续分析DOWN事件的流程:

DOWN事件:MainActivity.dispatchTouchEvent->MyViewGroup.dispatchTouchEvet->MyViewGroup.onInterceptTouchEvent->MyView.dispatchTouchEvent->setOnTouchListener.onTouch->MyView.onTouchEvent

UP事件:MainActivity.dispatchTouchEvent->MyViewGroup.dispatchTouchEvet->MyViewGroup.onInterceptTouchEvent->MyView.dispatchTouchEvent->setOnTouchListener.onTouch->MyView.onTouchEvent

从上面的执行流程可以看出当事件被MyView消费后,事件不会在往上传,后续的UP事件也直接通过dispatchTouchEvent分发给对应的View,这里还是提一下,在MainAcitivy中设置的setOnTouchListener中的onTouch事件是在MyView自身的onTouchEvent事件之前被执行,因而设置的setOnTouchEvent的onTouch函数还是会被执行。

先只分析这几种场景,MOVE事件和UP事件一样只要DOWN事件被某个View消耗了,那么MOVE事件也就直接传到这个View。可以下载代码运行后,在MyView上面滑动下看下Log,具体Log我也贴一份。

情况1:


情况2:


下面对着Android源码来具体分析View的触摸事件到底是怎么执行的。首先根据Log可以最先接收到消息的是Activity的dispatchTouchEvent,在该处设置断点,然后查看对应的调用方法栈(你会发现在调到MainActivity的dispatchTouchEvent时,前面已经调用了很多方法),如下:


由于Android系统启动后会先启动Zygote进程,该进程会在手机开机后一直运行,Android中的几个系统服务都是由Zygote进程fork出来的,一个应用在启动时所分配到的进程也是由Zygote进程fork出来的,通常说一个应用的起点是Application里面的onCreate函数,其实真正的起点是ActivityThread里面的main函数,看到这个main函数是不是有种熟悉的感觉啊。在main函数中初始化了应用程序的主线程,同时初始化了主线程的消息队列,并调用了Looper.loop()函数使主线程不断的对消息队列进行循环检测,有消息则进行处理。点击事件产生一个消息,该消息传到InputEventReceiver后,由InputEventReceiver的继承类WindowInputEventReceiver去处理,WindowInputEventReceiver类是ViewRootImpl类的内部类,查看对应代码如下:

ViewRootImpl.java

    final class WindowInputEventReceiver extends InputEventReceiver {        public WindowInputEventReceiver(InputChannel inputChannel, Looper looper) {            super(inputChannel, looper);        }        @Override        public void onInputEvent(InputEvent event) {            enqueueInputEvent(event, this, 0, true);        }        @Override        public void onBatchedInputEventPending() {            if (mUnbufferedInputDispatch) {                super.onBatchedInputEventPending();            } else {                scheduleConsumeBatchedInput();            }        }        @Override        public void dispose() {            unscheduleConsumeBatchedInput();            super.dispose();        }    }
查看代码可以当点击消息过来时,直接调用ViewRootImpl类中的enqueueInputEvent(event,this,0,true)方法:

ViewRootImpl.java

    void enqueueInputEvent(InputEvent event,            InputEventReceiver receiver, int flags, boolean processImmediately) {        adjustInputEventForCompatibility(event);        QueuedInputEvent q = obtainQueuedInputEvent(event, receiver, flags);        // Always enqueue the input event in order, regardless of its time stamp.        // We do this because the application or the IME may inject key events        // in response to touch events and we want to ensure that the injected keys        // are processed in the order they were received and we cannot trust that        // the time stamp of injected events are monotonic.        QueuedInputEvent last = mPendingInputEventTail;        if (last == null) {            mPendingInputEventHead = q;            mPendingInputEventTail = q;        } else {            last.mNext = q;            mPendingInputEventTail = q;        }        mPendingInputEventCount += 1;        Trace.traceCounter(Trace.TRACE_TAG_INPUT, mPendingInputEventQueueLengthCounterName,                mPendingInputEventCount);        if (processImmediately) {            doProcessInputEvents();        } else {            scheduleProcessInputEvents();        }    }
由于processImmediately为true,因而是立即处理,即直接调用doProcessInputEvents();

ViewRootImpl.java

    void doProcessInputEvents() {        // Deliver all pending input events in the queue.        while (mPendingInputEventHead != null) {            QueuedInputEvent q = mPendingInputEventHead;            mPendingInputEventHead = q.mNext;            if (mPendingInputEventHead == null) {                mPendingInputEventTail = null;            }            q.mNext = null;            mPendingInputEventCount -= 1;            Trace.traceCounter(Trace.TRACE_TAG_INPUT, mPendingInputEventQueueLengthCounterName,                    mPendingInputEventCount);            long eventTime = q.mEvent.getEventTimeNano();            long oldestEventTime = eventTime;            if (q.mEvent instanceof MotionEvent) {                MotionEvent me = (MotionEvent)q.mEvent;                if (me.getHistorySize() > 0) {                    oldestEventTime = me.getHistoricalEventTimeNano(0);                }            }            mChoreographer.mFrameInfo.updateInputEventTime(eventTime, oldestEventTime);            deliverInputEvent(q);        }        // We are done processing all input events that we can process right now        // so we can clear the pending flag immediately.        if (mProcessInputEventsScheduled) {            mProcessInputEventsScheduled = false;            mHandler.removeMessages(MSG_PROCESS_INPUT_EVENTS);        }    }
z之后调用了deliverInputEvent(q)

ViewRootImpl.java

    private void deliverInputEvent(QueuedInputEvent q) {        Trace.asyncTraceBegin(Trace.TRACE_TAG_VIEW, "deliverInputEvent",                q.mEvent.getSequenceNumber());        if (mInputEventConsistencyVerifier != null) {            mInputEventConsistencyVerifier.onInputEvent(q.mEvent, 0);        }        InputStage stage;        if (q.shouldSendToSynthesizer()) {            stage = mSyntheticInputStage;        } else {            stage = q.shouldSkipIme() ? mFirstPostImeInputStage : mFirstInputStage;        }        if (stage != null) {            stage.deliver(q);        } else {            finishInputEvent(q);        }    }
在这里初始化了一个InputStage类的实例,然后调用了该类的deliver(q),具体方法如下:

/**     * Base class for implementing a stage in the chain of responsibility     * for processing input events.     * <p>     * Events are delivered to the stage by the {@link #deliver} method.  The stage     * then has the choice of finishing the event or forwarding it to the next stage.     * </p>     */    abstract class InputStage {        private final InputStage mNext;        protected static final int FORWARD = 0;        protected static final int FINISH_HANDLED = 1;        protected static final int FINISH_NOT_HANDLED = 2;        /**         * Creates an input stage.         * @param next The next stage to which events should be forwarded.         */        public InputStage(InputStage next) {            mNext = next;        }        /**         * Delivers an event to be processed.         */        public final void deliver(QueuedInputEvent q) {            if ((q.mFlags & QueuedInputEvent.FLAG_FINISHED) != 0) {                forward(q);            } else if (shouldDropInputEvent(q)) {                finish(q, false);            } else {                apply(q, onProcess(q));            }        }        /**         * Marks the the input event as finished then forwards it to the next stage.         */        protected void finish(QueuedInputEvent q, boolean handled) {            q.mFlags |= QueuedInputEvent.FLAG_FINISHED;            if (handled) {                q.mFlags |= QueuedInputEvent.FLAG_FINISHED_HANDLED;            }            forward(q);        }        /**         * Forwards the event to the next stage.         */        protected void forward(QueuedInputEvent q) {            onDeliverToNext(q);        }        /**         * Applies a result code from {@link #onProcess} to the specified event.         */        protected void apply(QueuedInputEvent q, int result) {            if (result == FORWARD) {                forward(q);            } else if (result == FINISH_HANDLED) {                finish(q, true);            } else if (result == FINISH_NOT_HANDLED) {                finish(q, false);            } else {                throw new IllegalArgumentException("Invalid result: " + result);            }        }        /**         * Called when an event is ready to be processed.         * @return A result code indicating how the event was handled.         */        protected int onProcess(QueuedInputEvent q) {            return FORWARD;        }        /**         * Called when an event is being delivered to the next stage.         */        protected void onDeliverToNext(QueuedInputEvent q) {            if (DEBUG_INPUT_STAGES) {                Log.v(TAG, "Done with " + getClass().getSimpleName() + ". " + q);            }            if (mNext != null) {                mNext.deliver(q);            } else {                finishInputEvent(q);            }        }        protected boolean shouldDropInputEvent(QueuedInputEvent q) {            if (mView == null || !mAdded) {                Slog.w(TAG, "Dropping event due to root view being removed: " + q.mEvent);                return true;            } else if ((!mAttachInfo.mHasWindowFocus                    && !q.mEvent.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) || mStopped                    || (mPausedForTransition && !isBack(q.mEvent))) {                // This is a focus event and the window doesn't currently have input focus or                // has stopped. This could be an event that came back from the previous stage                // but the window has lost focus or stopped in the meantime.                if (isTerminalInputEvent(q.mEvent)) {                    // Don't drop terminal input events, however mark them as canceled.                    q.mEvent.cancel();                    Slog.w(TAG, "Cancelling event due to no window focus: " + q.mEvent);                    return false;                }                // Drop non-terminal input events.                Slog.w(TAG, "Dropping event due to no window focus: " + q.mEvent);                return true;            }            return false;        }        void dump(String prefix, PrintWriter writer) {            if (mNext != null) {                mNext.dump(prefix, writer);            }        }        private boolean isBack(InputEvent event) {            if (event instanceof KeyEvent) {                return ((KeyEvent) event).getKeyCode() == KeyEvent.KEYCODE_BACK;            } else {                return false;            }        }    }
对应方法栈可以看出,进过一些列调用最终会调用到ViewPostImeInputStage类的processPointerEvent方法.

ViewRootImpl.java

        private int processPointerEvent(QueuedInputEvent q) {            final MotionEvent event = (MotionEvent)q.mEvent;            mAttachInfo.mUnbufferedDispatchRequested = false;            boolean handled = mView.dispatchPointerEvent(event);            if (mAttachInfo.mUnbufferedDispatchRequested && !mUnbufferedInputDispatch) {                mUnbufferedInputDispatch = true;                if (mConsumeBatchedInputScheduled) {                    scheduleConsumeBatchedInputImmediately();                }            }            return handled ? FINISH_HANDLED : FORWARD;        }

在该方法中调用了mView的dispatchPointerEvent,这个mView的初始化可以查看Activity的创建代码,在Activity创建的时候会给Activity设置一个根布局也就是DecorView,这里的mView就是DecorView,这个DecorView是PhoneWindow的私有内部类,它继承于FrameLayout并实现了RootViewSurfaceTaker接口,但是该方法是View类的一个final方法,子类无法覆写,直接查看View中的相应代码即可。代码如下:

View.java

    /**     * Dispatch a pointer event.     * <p>     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches     * and should not be expected to handle other pointing device features.     * </p>     *     * @param event The motion event to be dispatched.     * @return True if the event was handled by the view, false otherwise.     * @hide     */    public final boolean dispatchPointerEvent(MotionEvent event) {        if (event.isTouchEvent()) {            return dispatchTouchEvent(event);        } else {            return dispatchGenericMotionEvent(event);        }    }

继续查看DecorView类中的dispatchTouchEvent方法,代码如下:

PhoneWindow.java

        @Override        public boolean dispatchTouchEvent(MotionEvent ev) {            final Callback cb = getCallback();            return cb != null && !isDestroyed() && mFeatureId < 0 ? cb.dispatchTouchEvent(ev)                    : super.dispatchTouchEvent(ev);        }
这个getCallback也就是当前的Activity,当当前Activity没有destroy的时候即调用该Activity的dispatchTouchEvent,这里代码就回到了应用层了,框架层完成了很多操作,这些操作只有查看源码才知道,这里终于回到了我们编写代码的地方了。当然这之后还是会通过框架层将对应的Touch事件传给对应的ViewGroup和View。下面先看下Activity中dispatchTouchEvent的代码:

Activity.java

    /**     * Called to process touch screen events.  You can override this to     * intercept all touch screen events before they are dispatched to the     * window.  Be sure to call this implementation for touch screen events     * that should be handled normally.     *     * @param ev The touch screen event.     *     * @return boolean Return true if this event was consumed.     */    public boolean dispatchTouchEvent(MotionEvent ev) {        if (ev.getAction() == MotionEvent.ACTION_DOWN) {            onUserInteraction();        }        if (getWindow().superDispatchTouchEvent(ev)) {//这个getWindow就是PhoneWindow,也就是通过PhoneWindow继续对touch事件进行分发。            return true;        }//当上面返回true,也就是View把事件消费了,那么就不再调用Activity的onTouchEvent函数了。        return onTouchEvent(ev);    }
果然这里又回到了框架层,这里getWindow就是PhoneWindow,继续查看PhoneWindow的代码:

PhoneWindow.java

    @Override    public boolean superDispatchTouchEvent(MotionEvent event) {        return mDecor.superDispatchTouchEvent(event);    }
这里把事件就传给了DecorView进行分发。

PhoneWindow.java->DecorView

        public boolean superDispatchTouchEvent(MotionEvent event) {            return super.dispatchTouchEvent(event);        }
前面说过DecorView继承于FrameLayout,这里super.dispatchTouchEvent就是调用了FrameLayout里面的dispatchTouchEvent,而FrameLayout类中并未重写dispatchTouchEvent,因而直接调用的是ViewGroup中的dispatchTouchEvent。继续查看代码:

ViewGroup.java

    /**     * {@inheritDoc}     */    @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);        }        boolean handled = false;        if (onFilterTouchEventForSecurity(ev)) {            final int action = ev.getAction();            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.                cancelAndClearTouchTargets(ev);                resetTouchState();            }            // Check for interception.            final boolean intercepted;            if (actionMasked == MotionEvent.ACTION_DOWN                    || mFirstTouchTarget != null) {                final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;                if (!disallowIntercept) {                    intercepted = onInterceptTouchEvent(ev);                    ev.setAction(action); // restore action in case it was changed                } else {                    intercepted = false;                }            } else {                // There are no touch targets and this action is not an initial down                // so this view group continues to intercept touches.                intercepted = true;            }            // 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 split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;            TouchTarget newTouchTarget = null;            boolean alreadyDispatchedToNewTouchTarget = false;            if (!canceled && !intercepted) {                // If the event is targeting accessiiblity 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);                    final int childrenCount = mChildrenCount;                    if (newTouchTarget == null && childrenCount != 0) {                        final float x = ev.getX(actionIndex);                        final float y = ev.getY(actionIndex);                        // Find a child that can receive the event.                        // Scan children from front to back.                        final ArrayList<View> preorderedList = buildOrderedChildList();                        final boolean customOrder = preorderedList == null                                && isChildrenDrawingOrderEnabled();                        final View[] children = mChildren;                        for (int i = childrenCount - 1; i >= 0; i--) {                            final int childIndex = customOrder                                    ? getChildDrawingOrder(childrenCount, i) : i;                            final View child = (preorderedList == null)                                    ? children[childIndex] : preorderedList.get(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);                            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) {                // 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;    }
代码有点多,通过调试可知将会调用dispatchTransformedTouchEvent,查看代码如下:

ViewGroup.java

    /**     * Transforms a motion event into the coordinate space of a particular child view,     * filters out irrelevant pointer ids, and overrides its action if necessary.     * If child is null, assumes the MotionEvent will be sent to this ViewGroup instead.     */    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) {                handled = super.dispatchTouchEvent(event);            } else {                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 {                    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) {            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;    }
在该函数中调用了child.dispatchTouchEvent(),这里便走到了子View的dispatchTouchEvent中。子View也就是MyView,也就走到了TextView的dispathTouchEvent中,由于TextView并未重写dispathTouchEvent,因而直接进入View的dispatchTouchEvent中,代码如下:

View.java

    /**     * Pass the touch screen motion event down to the target view, or this     * view if it is the target.     *     * @param event The motion event to be dispatched.     * @return True if the event was handled by the view, false otherwise.     */    public boolean dispatchTouchEvent(MotionEvent event) {        // 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)) {            //noinspection SimplifiableIfStatement            ListenerInfo li = mListenerInfo;            if (li != null && li.mOnTouchListener != null                    && (mViewFlags & ENABLED_MASK) == ENABLED                    && li.mOnTouchListener.onTouch(this, event)) {//在这里就调用了setOnTouchListener中的onTouch函数,如果有一个消费了,那么result=true                result = true;            }            if (!result && onTouchEvent(event)) {//当上面的result为true时,子View的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;    }

在该函数中看到了在MainActivity中设置的setOnTouchListener对应的Listener接口,当setListener中的onTouch返回true时,MyView本身的onTouchEvent便不被调用。接下来看下View的onTouchEvent代码:

View.java

public boolean onTouchEvent(MotionEvent event) {        final float x = event.getX();        final float y = event.getY();        final int viewFlags = mViewFlags;        final int action = event.getAction();        if ((viewFlags & ENABLED_MASK) == DISABLED) {            if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {                setPressed(false);            }            // A disabled view that is clickable still consumes the touch            // events, it just doesn't respond to them.            return (((viewFlags & CLICKABLE) == CLICKABLE                    || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)                    || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE);        }        if (mTouchDelegate != null) {//一个View还可以设置TouchDelegate,也可以在TouchDelegate的onTouchEvent里面处理点击事件            if (mTouchDelegate.onTouchEvent(event)) {                return true;            }        }        if (((viewFlags & CLICKABLE) == CLICKABLE ||                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) ||                (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) {            switch (action) {                case MotionEvent.ACTION_UP:                    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;                case MotionEvent.ACTION_DOWN:                    mHasPerformedLongPress = false;                    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();
                        //这个注意下,这里会调用ViewRootImpl内部函数也就是后面的MOVE为啥知道前面DOWN了
postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); } else { // Not inside a scrolling container, so show the feedback right away setPressed(true, x, y);
//这个去检查是否有长按事件
checkForLongClick(0); } break; case MotionEvent.ACTION_CANCEL: setPressed(false); removeTapCallback(); removeLongPressCallback(); mInContextButtonPress = false; mHasPerformedLongPress = false; mIgnoreNextUpEvent = false; break; case MotionEvent.ACTION_MOVE: drawableHotspotChanged(x, y); // Be lenient about moving outside of buttons if (!pointInView(x, y, mTouchSlop)) { // Outside button removeTapCallback(); if ((mPrivateFlags & PFLAG_PRESSED) != 0) { // Remove any future long press/tap checks removeLongPressCallback(); setPressed(false); } } break; } return true; } return false; }

这里仅分析下DOWN事件的处理,这里会先处理按钮自身的一些事件,具体事件见如下代码:

    /**     * Performs button-related actions during a touch down event.     *     * @param event The event.     * @return True if the down was consumed.     *     * @hide     */    protected boolean performButtonActionOnTouchDown(MotionEvent event) {        if (event.getToolType(0) == MotionEvent.TOOL_TYPE_MOUSE &&            (event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {            showContextMenu(event.getX(), event.getY(), event.getMetaState());            mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;            return true;        }        return false;    }
然后判断当前View的父View是否在滚动,如果不在滚动就调用postDelayed:

View.java

    public boolean postDelayed(Runnable action, long delayMillis) {        final AttachInfo attachInfo = mAttachInfo;        if (attachInfo != null) {            return attachInfo.mHandler.postDelayed(action, delayMillis);        }        // Assume that post will succeed later        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);        return true;    }
将action延迟一段时间,用于后续判断(是否长按事件,后续MOVE事件,UP事件)。
 
阅读全文
1 0
原创粉丝点击