Android事件分發(fā)、事件攔截、事件處理分析

事件機制在android開發(fā)中是比較常見的場景,比如:點擊、雙擊、長按、觸摸等,當然提到最多的就是View和ViewGroup的事件處理機制,事件處理機制包括:事件分發(fā)、事件攔截、事件處理,View包含:事件分發(fā)和事件處理,ViewGroup包含:事件分發(fā)、事件攔截、事件處理;接下來就看下當用于點擊或者觸摸默認控件(圖標)時事件的流程走向吧。
Activity中就包含一個自定義的LinearLayout和一個自定的View,重寫了Activity中的dispatchTouchEvent和onTouchEvent方法,

<?xml version="1.0" encoding="utf-8"?>
<com.lsm.gradlestudy.MyViewGroup xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.lsm.gradlestudy.MyView
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:text="Hello World!"
        android:background="@color/colorAccent"
        android:gravity="center" />

</com.lsm.gradlestudy.MyViewGroup>
@Override
    public boolean onTouchEvent(MotionEvent event) {
        int action = event.getAction();
        if (action == MotionEvent.ACTION_DOWN) {
            Log.d(TAG, "事件處理----onTouchEvent----按下了");
        } else if (action == MotionEvent.ACTION_UP) {
            Log.d(TAG, "事件處理----onTouchEvent----抬起了");
        } else if (action == MotionEvent.ACTION_MOVE) {
            Log.d(TAG, "事件處理----onTouchEvent----移動了");
        }
        //返回true或者false 或者系統(tǒng)的默認值 都代表對事件的消費,
        //不過返回false的話不會有MotionEvent.ACTION_MOVE
        return super.onTouchEvent(event);
    }
@Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        int action = ev.getAction();
        if (action == MotionEvent.ACTION_DOWN) {
            Log.d(TAG, "事件處理----dispatchTouchEvent----按下了");
        } else if (action == MotionEvent.ACTION_UP) {
            Log.d(TAG, "事件處理----dispatchTouchEvent----抬起了");
        } else if (action == MotionEvent.ACTION_MOVE) {
            Log.d(TAG, "事件處理----dispatchTouchEvent----移動了");
        }
        //這里如果返回true或者false就不會對事件進行分發(fā),后面的ViewGroup和View就響應不到事件了
        return super.dispatchTouchEvent(ev);
    }

自定義ViewGroup中重寫了dispatchTouchEvent、onTouchEvent、onTnterceptTouchEvent方法,

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

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

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

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

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

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

自定義View重寫了dispatchTouchEvent、onTouchEvent方法,

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

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

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

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

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

上面重寫的方法的返回值沒有做修改,返回的都是系統(tǒng)默認的值,看下打印的日志輸出,

事件機制.png

首先響應的是activity中的方法,然后是ViewGroup,最后才是點擊的View控件,直到事件被消費掉,通過之前對setContentView源碼的分析得知,用戶看的界面,依次為:

PhoneWindow(Window)--->DecorView(FrameLayout)--->R.id.content(系統(tǒng)布局容器)--->自定義的布局容器--->自定義的View控件

所以得到:

其實就是ViewGroup一直將事件傳遞分發(fā)下去直到事件被攔截或者消費掉為止。

既然這樣的話,如果activity中的dispatchTouchEvent返回true或者false的話,就不會將事件分發(fā)下去,后面的ViewGroup和View也就響應不到事件了,


事件機制0.png

這個是返回true,返回false少了MotionEvent.ACTION_MOVE,activity中onTouchEvent返回true或者false 或這系統(tǒng)默認值,都是對事件進行消費,返回false會少了MotionEvent.ACTION_MOVE。在activity的dispatchTouchEvent中可以看到會調(diào)用Window中的superDispatchTouchEvent方法

public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            //在activity中可以重寫該方法,執(zhí)行一些action_down后的邏輯
            onUserInteraction();
        }
    //調(diào)用window中的方法
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
    //調(diào)用onTouchEvent方法,判斷事件是否被消費掉 
    //如果沒有消費掉就繼續(xù)分發(fā)  如果消費掉了就停止分發(fā)
        return onTouchEvent(ev);
    }
@Override
    public boolean superDispatchTouchEvent(MotionEvent event) {
        //調(diào)用了DecorView中的superDispatchTouchEvent方法
        return mDecor.superDispatchTouchEvent(event);
    }

在PhoneWindow中看到接著調(diào)用到了DecorView中的superDispatchTouchEvent方法,DecorView其實是繼承自ViewGroup的,那其實調(diào)用的就是ViewGroup中的dispatchTouchEvent方法,

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

        // If the event targets the accessibility focused view and this is it, start
        // normal event dispatch. Maybe a descendant is what will handle the click.
        if (ev.isTargetAccessibilityFocus() && isAccessibilityFocusedViewOrHost()) {
            ev.setTargetAccessibilityFocus(false);
        }
        //用于標記dispatchTouchEvent的返回值
        boolean handled = false;
        //過濾掉一些事件處理,true代表需要處理  false代表過濾
        if (onFilterTouchEventForSecurity(ev)) {
            //獲取當前對應的事件類型 比如 是down還是up等
            final int action = ev.getAction();
            //獲取對應事件類型的mask
            final int actionMasked = action & MotionEvent.ACTION_MASK;

            // Handle an initial down.
            if (actionMasked == MotionEvent.ACTION_DOWN) {
                // Throw away all previous state when starting a new touch gesture.
                // The framework may have dropped the up or cancel event for the previous gesture
                // due to an app switch, ANR, or some other state change.
                //取消和清除之前的touchTarget  在這里mFirstTouchTarget會被設置為null
                cancelAndClearTouchTargets(ev);
                //恢復事件的狀態(tài)
                resetTouchState();
            }
            //標識檢查時間是否被攔截
            // Check for interception.
            final boolean intercepted;
            if (actionMasked == MotionEvent.ACTION_DOWN
                    || mFirstTouchTarget != null) {
                //FLAG_DISALLOW_INTERCEPT 是否允許攔截的標識
                final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
                if (!disallowIntercept) {
                    //交由onInterceptTouchEvent 來覺得是否進行攔截 可以在子類中重寫該方法 進行事件的攔截
                    intercepted = onInterceptTouchEvent(ev);
                    //設置事件類型
                    ev.setAction(action); // restore action in case it was changed
                } else {
                    intercepted = false;
                }
            } else {
                // There are no touch targets and this action is not an initial down
                // so this view group continues to intercept touches.
                //沒有觸摸的目標,并且不是最初的 就直接攔截該view
                intercepted = true;
            }

            // If intercepted, start normal event dispatch. Also if there is already
            // a view that is handling the gesture, do normal event dispatch.
            if (intercepted || mFirstTouchTarget != null) {
                ev.setTargetAccessibilityFocus(false);
            }
            //檢測事件是否被取消
            // Check for cancelation.
            final boolean canceled = resetCancelNextUpFlag(this)
                    || actionMasked == MotionEvent.ACTION_CANCEL;

            // Update list of touch targets for pointer down, if needed.
            final boolean isMouseEvent = ev.getSource() == InputDevice.SOURCE_MOUSE;
            final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0
                    && !isMouseEvent;
            //定義事件目標實例對象
            TouchTarget newTouchTarget = null;
            boolean alreadyDispatchedToNewTouchTarget = false;
            //如果事件沒有被取消 并且沒有被攔截 這個時候根據(jù)需要進行事件的分發(fā)和處理
            if (!canceled && !intercepted) {
                // If the event is targeting accessibility focus we give it to the
                // view that has accessibility focus and if it does not handle it
                // we clear the flag and dispatch the event to all children as usual.
                // We are looking up the accessibility focused host to avoid keeping
                // state since these events are very rare.
                View childWithAccessibilityFocus = ev.isTargetAccessibilityFocus()
                        ? findChildWithAccessibilityFocus() : null;

                if (actionMasked == MotionEvent.ACTION_DOWN
                        || (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)
                        || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
                    final int actionIndex = ev.getActionIndex(); // always 0 for down
                    final int idBitsToAssign = split ? 1 << ev.getPointerId(actionIndex)
                            : TouchTarget.ALL_POINTER_IDS;

                    // Clean up earlier touch targets for this pointer id in case they
                    // have become out of sync.
                    removePointersFromTouchTargets(idBitsToAssign);
                    //獲取childview的數(shù)量
                    final int childrenCount = mChildrenCount;
                    //如果事件目標為null 同事布局中有子view
                    if (newTouchTarget == null && childrenCount != 0) {
                        //獲取事件目標在屏幕中的位置
                        final float x =
                                isMouseEvent ? ev.getXCursorPosition() : ev.getX(actionIndex);
                        final float y =
                                isMouseEvent ? ev.getYCursorPosition() : ev.getY(actionIndex);
                        // Find a child that can receive the event.
                        // Scan children from front to back.
                        //尋找對應事件的view,從前到后的方式遍歷view
                        //構(gòu)建事件觸摸分發(fā)處理子view列表
                        final ArrayList<View> preorderedList = buildTouchDispatchChildList();
                        final boolean customOrder = preorderedList == null
                                && isChildrenDrawingOrderEnabled();
                        //獲取容器中view
                        final View[] children = mChildren;
                        //進行對布局中view的遍歷
                        for (int i = childrenCount - 1; i >= 0; i--) {
                            final int childIndex = getAndVerifyPreorderedIndex(
                                    childrenCount, i, customOrder);
                            //獲取對應位置的view,如果不是事件對應的view 就跳過去
                            final View child = getAndVerifyPreorderedView(
                                    preorderedList, children, childIndex);
                            if (!child.canReceivePointerEvents()
                                    || !isTransformedTouchPointInView(x, y, child, null)) {
                                continue;
                            }
                            //獲取view的事件目標
                            newTouchTarget = getTouchTarget(child);
                            if (newTouchTarget != null) {
                                // Child is already receiving touch within its bounds.
                                // Give it the new pointer in addition to the ones it is handling.
                                newTouchTarget.pointerIdBits |= idBitsToAssign;
                                break;
                            }
                            //重置一些取消的標識
                            resetCancelNextUpFlag(child);
                            //轉(zhuǎn)換事件處理
                            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;
                    }
                }
            }
            //事件分發(fā)目標
            // Dispatch to touch targets.
            if (mFirstTouchTarget == null) {
                //第一次 或者處理完一次后事件分發(fā)目標肯定是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;
    }

在執(zhí)行事件分發(fā)邏輯時,ViewGroup會去判斷是否要對View進行事件攔截,如果進行了攔截,就沒有后面View的事件分發(fā)和處理了,

public boolean onInterceptTouchEvent(MotionEvent ev) {
        if (ev.isFromSource(InputDevice.SOURCE_MOUSE)
                && ev.getAction() == MotionEvent.ACTION_DOWN
                && ev.isButtonPressed(MotionEvent.BUTTON_PRIMARY)
                && isOnScrollbarThumb(ev.getX(), ev.getY())) {
            return true;
        }
        return false;
    }

事件攔截默認返回false,是不攔截的,如果需要攔截view的事件,在對應的布局容器中重寫onInterceptTouchEvent返回true,如果事件沒有被取消,也沒有被攔截,第一次mFirstTouchTarget肯定是null的,就會調(diào)用

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

mFirstTouchTarget是一個TouchTarget實例對象,是用于描述和存儲事件目標view的,使用的是單項鏈表的結(jié)構(gòu),

private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
            View child, int desiredPointerIdBits) {
        final boolean handled;
        // Canceling motions is a special case.  We don't need to perform any transformations
        // or filtering.  The important part is the action, not the contents.
        final int oldAction = event.getAction();
        if (cancel || oldAction == MotionEvent.ACTION_CANCEL) {
            //如果是事件取消的話  設置事件的類型
            event.setAction(MotionEvent.ACTION_CANCEL);
            if (child == null) {
                //view為null 直接調(diào)用ViewGroup的父類的事件分發(fā)
                handled = super.dispatchTouchEvent(event);
            } else {
                //調(diào)用view child的事件分發(fā)
                handled = child.dispatchTouchEvent(event);
            }
            event.setAction(oldAction);
            //將分發(fā)結(jié)果返回
            return handled;
        }

        // Calculate the number of pointers to deliver.
        final int oldPointerIdBits = event.getPointerIdBits();
        final int newPointerIdBits = oldPointerIdBits & desiredPointerIdBits;

        // If for some reason we ended up in an inconsistent state where it looks like we
        // might produce a motion event with no pointers in it, then drop the event.
        if (newPointerIdBits == 0) {
            return false;
        }

        // If the number of pointers is the same and we don't need to perform any fancy
        // irreversible transformations, then we can reuse the motion event for this
        // dispatch as long as we are careful to revert any changes we make.
        // Otherwise we need to make a copy.
        final MotionEvent transformedEvent;
        if (newPointerIdBits == oldPointerIdBits) {
            if (child == null || child.hasIdentityMatrix()) {
                if (child == null) {
                    handled = super.dispatchTouchEvent(event);
                } else {
                    //計算view事件的坐標
                    final float offsetX = mScrollX - child.mLeft;
                    final float offsetY = mScrollY - child.mTop;
                    event.offsetLocation(offsetX, offsetY);

                    handled = child.dispatchTouchEvent(event);

                    event.offsetLocation(-offsetX, -offsetY);
                }
                return handled;
            }
            transformedEvent = MotionEvent.obtain(event);
        } else {
            transformedEvent = event.split(newPointerIdBits);
        }

        // Perform any necessary transformations and dispatch.
        if (child == null) {
            //第一次的時候child肯定是null的
            handled = super.dispatchTouchEvent(transformedEvent);
        } else {
            final float offsetX = mScrollX - child.mLeft;
            final float offsetY = mScrollY - child.mTop;
            transformedEvent.offsetLocation(offsetX, offsetY);
            if (! child.hasIdentityMatrix()) {
                transformedEvent.transform(child.getInverseMatrix());
            }

            handled = child.dispatchTouchEvent(transformedEvent);
        }

        // Done.
        transformedEvent.recycle();
        return handled;
    }

看到最終會交互view或者ViewGroup的父類的dispatchTouchEvent去進行事件分發(fā)的處理,

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);
        }
    //定義事件分發(fā)的結(jié)果標識
        boolean result = false;

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

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

        if (onFilterTouchEventForSecurity(event)) {
            if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
                result = true;
            }
            //noinspection SimplifiableIfStatement
            //監(jiān)聽觸摸等的實例對象
            ListenerInfo li = mListenerInfo;
            if (li != null && li.mOnTouchListener != null
                    && (mViewFlags & ENABLED_MASK) == ENABLED
                    && li.mOnTouchListener.onTouch(this, event)) {
                //代表對該事件進行了消費
                result = true;
            }
            //如果result為false 會通過onTouchEvent看看對該事件有沒有進行消費
            if (!result && onTouchEvent(event)) {
                result = true;
            }
        }

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

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

        return result;
    }

ListenerInfo是一個靜態(tài)的管理一些了事件監(jiān)聽的類,其中就包含了OnTouchListener,可以給對應的View或者ViewGroup設置OnTouchListener來達到事件消費的目的,

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

如果并沒有設置OnTouchListener就會通過onTouchEvent看看有沒有對該事件進行消費,

public boolean onTouchEvent(MotionEvent event) {
    //獲取事件的范圍
        final float x = event.getX();
        final float y = event.getY();
        final int viewFlags = mViewFlags;
    //獲取事件的類型
        final int action = event.getAction();
        //是否是可點擊的
        final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE
                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;

        if ((viewFlags & ENABLED_MASK) == DISABLED) {
            if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
                setPressed(false);
            }
            mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
            // A disabled view that is clickable still consumes the touch
            // events, it just doesn't respond to them.
            return clickable;
        }
        if (mTouchDelegate != null) {
            if (mTouchDelegate.onTouchEvent(event)) {
                return true;
            }
        }

        if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
            switch (action) {
                case MotionEvent.ACTION_UP:
                    mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
                    if ((viewFlags & TOOLTIP) == TOOLTIP) {
                        handleTooltipUp();
                    }
                    if (!clickable) {
                        removeTapCallback();
                        removeLongPressCallback();
                        mInContextButtonPress = false;
                        mHasPerformedLongPress = false;
                        mIgnoreNextUpEvent = false;
                        break;
                    }
                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
                        // take focus if we don't have it already and we should in
                        // touch mode.
                        boolean focusTaken = false;
                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
                            focusTaken = requestFocus();
                        }

                        if (prepressed) {
                            // The button is being released before we actually
                            // showed it as pressed.  Make it show the pressed
                            // state now (before scheduling the click) to ensure
                            // the user sees it.
                            setPressed(true, x, y);
                        }

                        if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
                            // This is a tap, so remove the longpress check
                            removeLongPressCallback();

                            // Only perform take click actions if we were in the pressed state
                            if (!focusTaken) {
                                // Use a Runnable and post this rather than calling
                                // performClick directly. This lets other visual state
                                // of the view update before click actions start.
                                //創(chuàng)建PerformClick實例
                                if (mPerformClick == null) {
                                    mPerformClick = new PerformClick();
                                }
                                if (!post(mPerformClick)) {
                                    //調(diào)用該方法通過點擊事件的觸發(fā)來進行事件的消費
                                    performClickInternal();
                                }
                            }
                        }

                        if (mUnsetPressedState == null) {
                            mUnsetPressedState = new UnsetPressedState();
                        }

                        if (prepressed) {
                            postDelayed(mUnsetPressedState,
                                    ViewConfiguration.getPressedStateDuration());
                        } else if (!post(mUnsetPressedState)) {
                            // If the post failed, unpress right now
                            mUnsetPressedState.run();
                        }

                        removeTapCallback();
                    }
                    mIgnoreNextUpEvent = false;
                    break;

                case MotionEvent.ACTION_DOWN:
                    if (event.getSource() == InputDevice.SOURCE_TOUCHSCREEN) {
                        mPrivateFlags3 |= PFLAG3_FINGER_DOWN;
                    }
                    mHasPerformedLongPress = false;

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

                    if (performButtonActionOnTouchDown(event)) {
                        break;
                    }

                    // Walk up the hierarchy to determine if we're inside a scrolling container.
                    boolean isInScrollingContainer = isInScrollingContainer();

                    // For views inside a scrolling container, delay the pressed feedback for
                    // a short period in case this is a scroll.
                    if (isInScrollingContainer) {
                        mPrivateFlags |= PFLAG_PREPRESSED;
                        if (mPendingCheckForTap == null) {
                            mPendingCheckForTap = new CheckForTap();
                        }
                        mPendingCheckForTap.x = event.getX();
                        mPendingCheckForTap.y = event.getY();
                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
                    } else {
                        // Not inside a scrolling container, so show the feedback right away
                        setPressed(true, x, y);
                        checkForLongClick(
                                ViewConfiguration.getLongPressTimeout(),
                                x,
                                y,
                                TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__LONG_PRESS);
                    }
                    break;

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

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

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

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

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

                    break;
            }

            return true;
        }

        return false;
    }

當事件類型為ACTION_UP的時候就會創(chuàng)建一個PerformClick實例對象,并調(diào)用performClickInternal方法通過click點擊方式來消費該事件,

public boolean performClick() {
        // We still need to call this method to handle the cases where performClick() was called
        // externally, instead of through performClickInternal()
        notifyAutofillManagerOnClick();

        final boolean result;
        final ListenerInfo li = mListenerInfo;
        if (li != null && li.mOnClickListener != null) {
            playSoundEffect(SoundEffectConstants.CLICK);
            li.mOnClickListener.onClick(this);
            result = true;
        } else {
            result = false;
        }

        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);

        notifyEnterOrExitForAutoFillIfNeeded(true);

        return result;
    }

這里就會我們平時通過setOnClickListener點擊事件,然后重寫onClick方法方式去消費對應的點擊事件,上面是TouchTarget為null且child為null的情況,如果childCount不為0的時候,在按下的時候會從前到后一次遍歷每個view,同時獲取對應的TouchTarget,

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

如果轉(zhuǎn)換得到的view有對應的事件要處理,會添加綁定對應的TouchTarget,

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

這樣子一直到事件被消費處理掉。

總結(jié):
1、View只有事件分發(fā)(dispatchTouchEvent)和事件處理(onTouchEvent),ViewGroup有事件分發(fā)(dispatchTouchEvent)、事件攔截(onInterceptTouchEvent)、事件處理(onTouchEvent)
2、正常事件流程:dispatchTouchEvent(事件分發(fā))--->onInterceptTouchEvent(事件攔截)->onTouchEvent(事件處理)--->OnTouchListener(事件觸摸)--->onClick(事件點擊),這里說的正常流程都是系統(tǒng)返回的默認值
3、onInterceptTouchEvent返回值為true,事件會被攔截掉,后面的流程都會被終止掉
4、OnTouchListener返回true,代表事件被消費掉,onClick不會被執(zhí)行
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容