android TouchEvent分發(fā)筆記

關(guān)于android的觸摸事件這個知識點,一直感覺掌握不牢固淡诗,趁著前幾天有空絮姆,就仔細了看了一遍源碼,順便寫了一下筆記蓖宦,本來不想發(fā)成博客,但考慮到有些可能分析的不對油猫,所以發(fā)出來稠茂,希望大家多多指出問題,如果對你有少許的幫助,那就太好了睬关。
本篇文章是基于android sdk 25的分析诱担。
github

ACTION_DOWN或ACTION_POINTER_DOWN和ACTION_HOVER_MOVE 這三個事件稱為初始事件,因為只有在分發(fā)這三個事件時候电爹,才會處理觸摸目標蔫仙。

ACTION_POINTER_DOWN和ACTION_HOVER_MOVE這兩個稱為多指初始事件

觸摸目標指消費了初始事件的子視圖丐箩,數(shù)據(jù)結(jié)構(gòu)為鏈表摇邦。新增加的子視圖為存放在頭部。

viewFlags & CLICKABLE == CLICKABLE || viewFlags & LONG_CLICKABLE == LONG_CLICKABLE || viewFlags & CONTEXT_CLICKABLE == CONTEXT_CLICKABLE 表示該視圖是 "可點擊的"屎勘。

  1. Android的Touch事件由Activity->ViewGroup-View按順序分發(fā)(這里只關(guān)心到Activity)
  2. 父視圖可以通過onInterceptTouchEvent來攔截事件分發(fā)到子視圖
  3. 子視圖可以調(diào)用requestDisallowInterceptTouchEvent來禁止父視圖攔截事件施籍,但在ACTION_DOWN時,會清除該標記概漱,即只在ACTION_DOWN時丑慎,調(diào)用該方法沒有效果。
  4. 如果子視圖沒有調(diào)用requestDisallowInterceptTouchEvent犀概,那么父視圖任何時候都可以攔截事件立哑,即使子視圖已經(jīng)消費了ACTION_DOWN,攔截事件后姻灶,會向子視圖分發(fā)一個ACTION_CANCEL事件
  5. 父視圖分發(fā)事件時铛绰,只會在初始事件時候,來設(shè)置觸摸目標产喉。即如果子視圖沒消費這三個事件捂掰,也不會接收到后續(xù)的事件。
  6. 當分發(fā)多指初始事件時曾沈,沒有新的子視圖來消費該事件時这嚣,會將該事件的指針賦予觸摸目標的尾部。
  7. 當沒有子視圖來消費事件時塞俱,會將事件分發(fā)給父視圖姐帚。(super.dispatchTouchEvent)
  8. View的事件分發(fā),OnTouchListener.onTouch -> onTouchEvent -> TouchDelegate.onTouchEvent -> onClick/onLongClick等等
  9. 只要視圖是可點擊的就默認會消費事件障涯,即使該視圖是不啟用的(setEnabled(false))罐旗,只是不做點擊處理反應(yīng)。

Activity中

public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            //用戶交互回調(diào)
            onUserInteraction();
        }
        if (getWindow().superDispatchTouchEvent(ev)) {
           //window是否消費該事件,touch事件分發(fā)從這里開始
            return true;
        }
        //當前view沒有消費事件唯蝶,則由activity處理
        return onTouchEvent(ev);
    }

//當前沒有任何view去消費事件時
public boolean onTouchEvent(MotionEvent event) {
        //window是否消費該事件九秀,來關(guān)閉當前window
        if (mWindow.shouldCloseOnTouch(this, event)) {
            finish();
            return true;
        }

        return false;
    }

PhoneWindow中

@Override
  public boolean superDispatchTouchEvent(MotionEvent event) {
        //window將事件委托給DecorView分發(fā)
        return mDecor.superDispatchTouchEvent(event);
    }

DecorView中

 public boolean superDispatchTouchEvent(MotionEvent event) {
        //調(diào)用父類的dispatchTouchEvent進行分發(fā)
        return super.dispatchTouchEvent(event);
    }

ViewGroup中

@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);
        }
        //從這里開始事件分發(fā)
        boolean handled = false;
        //安全策略過濾
        if (onFilterTouchEventForSecurity(ev)) {
            final int action = ev.getAction();
            //多指處理
            //多指情況下,POINTER:指針粘我。(可以理解為單個手指)
            final int actionMasked = action & MotionEvent.ACTION_MASK;

            // Handle an initial down.
            //處理一個初始按下事件ACTION_DOWN
            if (actionMasked == MotionEvent.ACTION_DOWN) {
              //丟棄之前的狀態(tài)
                // 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);
              //重置觸摸狀態(tài),這里會將使用requestDisallowInterceptTouchEvent設(shè)置的狀態(tài)清除
              //這個狀態(tài)可以阻止父視圖(通過onInterceptTouchEvent)攔截子視圖Touch事件
                resetTouchState();
            }

            // Check for interception.
            //檢查是否攔截
            final boolean intercepted;
            //當為ACTION_DEON事件或觸摸目標為不為null
            //即使已經(jīng)有子視圖消費了事件,依然會執(zhí)行判斷
            if (actionMasked == MotionEvent.ACTION_DOWN
                    || mFirstTouchTarget != null) {
                //檢查子視圖是否調(diào)用了requestDisallowInterceptTouchEvent來禁止父視圖攔截
                //這個標記為ACTION_DOWN處理中被清除都弹,即子視圖在ACTION_DOWN中調(diào)用是不起作用
                final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
                if (!disallowIntercept) {
                    //檢查當前父視圖是否攔截該事件
                    intercepted = onInterceptTouchEvent(ev);
                    //恢復(fù)action娇豫,以防止在onInterceptTouchEvent被改變
                    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.
                //當前不是ACTION_DOWN事件,且沒有觸摸目標
                //即子視圖如果不消費ACTION_DOWN畅厢,那么后續(xù)事件也不會分發(fā)到锤躁。
                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.
            //檢查是否為ACTION_CANCEL事件
            final boolean canceled = resetCancelNextUpFlag(this)
                    || actionMasked == MotionEvent.ACTION_CANCEL;

            // Update list of touch targets for pointer down, if needed.
            //檢查是否把事件分發(fā)給多個子視圖
            //通過setMotionEventSplittingEnabled設(shè)置,Android3.0以上默認開啟
            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;
                //1.當ACTION_DOWN事件(第一次按下)
                //2.或事件可以分發(fā)給多個子視圖且ACTION+POINTER_DOWN(多指處理或详,當主指針還沒結(jié)束,又按下一個指針)
                //3.或多指情況下郭计,指針移動
                //這里的判斷表示霸琴,只有在ACTION_DOWN或者當前事件分發(fā)還沒結(jié)束,出現(xiàn)新的指針事件才會進行分發(fā)昭伸。但這里的前提依然是梧乘,事件未取消和父視圖不攔截,和至少接收了ACTION_DOWN事件(即觸摸目標鏈表不為空庐杨,ACTION_DOWN事件除外)
                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
                    //指針id的位掩碼(用于獲取觸摸目標捕獲的指針)
                    //TouchTarget.pointerIdBis 指針id的組合位掩碼选调,用于目標捕獲的所有指針
                    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.
                        //獲取子視圖的事件分發(fā)列表
                        //這里考慮了自定義的子視圖繪制順序
                        final ArrayList<View> preorderedList = buildTouchDispatchChildList();
                      //TODO:按buildTouchDispatchChildList()的返回 != null,即customOrder永遠為false灵份,即自定義了繪制順序也不會改變事件分發(fā)順序
                      final boolean customOrder = preorderedList == null
                                && isChildrenDrawingOrderEnabled();
                        final View[] children = mChildren;
                        for (int i = childrenCount - 1; i >= 0; i--) {
                            final int childIndex = getAndVerifyPreorderedIndex(
                                    childrenCount, i, customOrder);
                            final View child = getAndVerifyPreorderedView(
                                    preorderedList, children, childIndex);

                            // If there is a view that has accessibility focus we want it
                            // to get the event first and if not handled we will perform a
                            // normal dispatch. We may do a double iteration but this is
                            // safer given the timeframe.
                            //輔助功能
                            if (childWithAccessibilityFocus != null) {
                                if (childWithAccessibilityFocus != child) {
                                    continue;
                                }
                                childWithAccessibilityFocus = null;
                                i = childrenCount - 1;
                            }
                            
                            //檢查子視圖是否可以接受事件和觸摸事件是否作用在子視圖上
                            if (!canViewReceivePointerEvents(child)
                                    || !isTransformedTouchPointInView(x, y, child, null)) {
                                ev.setTargetAccessibilityFocus(false);
                                continue;
                            }
                            
                            //檢查當前子視圖是否已經(jīng)存在觸摸目標鏈表中
                            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.
                                //如果已經(jīng)存在仁堪,則將新指針id賦值給它,并退出循環(huán)
                                newTouchTarget.pointerIdBits |= idBitsToAssign;
                                break;
                            }
                            //檢查是否設(shè)置了取消標記
                            //TODO:但這里沒對結(jié)果進行處理
                            resetCancelNextUpFlag(child);
                            //在這里將事件交予子視圖進行分發(fā)
                            //一般能執(zhí)行到這里的:
                            //1.ACTION_DOWN
                            //2.多指情況下填渠,指針作用于"新"視圖上
                            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();
                                //設(shè)置接收事件的子視圖為新的觸摸目標弦聂,并設(shè)置為觸摸目標鏈表的頭
                                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.
                        //當觸摸目標鏈表不為空,且當前事件沒有產(chǎn)生新的觸摸目標(包含已有的觸摸目標)來接收
                        newTouchTarget = mFirstTouchTarget;
                        while (newTouchTarget.next != null) {
                            newTouchTarget = newTouchTarget.next;
                        }
                        //找到觸摸目標鏈表的尾部氛什,將指針作用于它
                        newTouchTarget.pointerIdBits |= idBitsToAssign;
                    }
                }
            }

            // Dispatch to touch targets.
            //除了ACTION_DOWN莺葫,ACTION_POINTER_DOWN,ACTION_HOVER_MOVE
            //其他的事件的分發(fā)都從這里
            if (mFirstTouchTarget == null) {
                // No touch targets so treat this as an ordinary view.
                //沒有子視圖接收事件,將事件分發(fā)給當前視圖
                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.
                //將事件分發(fā)給觸摸目標枪眉,除了新的觸摸目標捺檬,因為在之前已經(jīng)分發(fā)了
                TouchTarget predecessor = null;
                TouchTarget target = mFirstTouchTarget;
                while (target != null) {
                    final TouchTarget next = target.next;
                    if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
                        //新的觸摸目標,直接跳過
                        handled = true;
                    } else {
                        //檢查事件是否被取消或者被攔截
                        //即使子視圖在ACTION_DOWN中接收了事件贸铜,如果沒禁止攔截堡纬,父視圖依然可以攔截事件
                        final boolean cancelChild = resetCancelNextUpFlag(target.child)
                                || intercepted;
                        //分發(fā)到觸摸目標
                        //當cancelChild=true,會分發(fā)ACTION_CANCEL事件
                        //dispatchTransformedTouchEvent中會判斷當前觸摸目標是否包含指針id
                        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;
    }
//取消和清除所有觸摸目標
private void cancelAndClearTouchTargets(MotionEvent event) {
        if (mFirstTouchTarget != null) {
            boolean syntheticEvent = false;
            if (event == null) {
                final long now = SystemClock.uptimeMillis();
                //獲取一個ACTION_CANCEL事件
                event = MotionEvent.obtain(now, now,
                        MotionEvent.ACTION_CANCEL, 0.0f, 0.0f, 0);
                event.setSource(InputDevice.SOURCE_TOUCHSCREEN);
                syntheticEvent = true;
            }

            for (TouchTarget target = mFirstTouchTarget; target != null; target = target.next) {
                resetCancelNextUpFlag(target.child);
               //分發(fā)ACTION_CANCEL事件
                dispatchTransformedTouchEvent(event, true, target.child, target.pointerIdBits);
            }
            clearTouchTargets();

            if (syntheticEvent) {
                event.recycle();
            }
        }
    }
//清除所有觸摸目標
 private void clearTouchTargets() {
        TouchTarget target = mFirstTouchTarget;
        if (target != null) {
            do {
                TouchTarget next = target.next;
                target.recycle();
                target = next;
            } while (target != null);
            mFirstTouchTarget = null;
        }
    }
//將事件分發(fā)到相應(yīng)的目標
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.
        //當事件取消時萨脑,會根據(jù)是否有觸摸目標隐轩,向當前視圖或子視圖分發(fā)一個ACTION_CANCEL事件
        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.
        //該觸摸目標不包含該指針,不分發(fā)
        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.
        //將事件進行分發(fā),根據(jù)是否有觸摸目標
        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;
    }

View中

public boolean dispatchTouchEvent(MotionEvent event) {
        //輔助功能
        // If the event should be handled by accessibility focus first.
        if (event.isTargetAccessibilityFocus()) {
            // We don't have focus or no virtual descendant has it, do not handle the event.
            if (!isAccessibilityFocusedViewOrHost()) {
                return false;
            }
            // We have focus and got the event, then use normal event dispatch.
            event.setTargetAccessibilityFocus(false);
        }

        boolean result = false;
        
        //調(diào)試作用
        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
            //先調(diào)用OnTouchListener回調(diào)
            ListenerInfo li = mListenerInfo;
            if (li != null && li.mOnTouchListener != null
                    && (mViewFlags & ENABLED_MASK) == ENABLED
                    && li.mOnTouchListener.onTouch(this, event)) {
                result = true;
            }
            
            //如果沒有OnTouchListener或者沒有消費渤早,則調(diào)用onTouchEvent
            if (!result && onTouchEvent(event)) {
                result = true;
            }
        }
    
        //調(diào)試
        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.
        //當ACTION_UP职车,ACTION_CANCEL或ACTION_DOWN且不消費,停止嵌套滾動
        if (actionMasked == MotionEvent.ACTION_UP ||
                actionMasked == MotionEvent.ACTION_CANCEL ||
                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
            stopNestedScroll();
        }

        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();

        if ((viewFlags & ENABLED_MASK) == DISABLED) {
            //當該視圖不啟用時(setEnabled(false))
            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.
            //不啟用的視圖依然可以消費事件,只是沒有反應(yīng)而已悴灵。
            //只要該視圖是 "可點擊的"
            return (((viewFlags & CLICKABLE) == CLICKABLE
                    || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
                    || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE);
        }
        //調(diào)用TouchDelegate
        if (mTouchDelegate != null) {
            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) {
                        //當我們設(shè)置 "按下" 狀態(tài)或 "延時按下" 狀態(tài)
                        // 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.
                            //如果設(shè)置了 "延時按下" 狀態(tài)扛芽,那在實際釋放之前設(shè)置為 "按下" 狀態(tài)
                            setPressed(true, x, y);
                       }

                        if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
                            //如果沒有調(diào)用長按動作而且不忽略下一個抬起的事件,清除長按回調(diào)积瞒,不回調(diào)長按事件
                            // This is a tap, so remove the longpress check
                            removeLongPressCallback();

                            // Only perform take click actions if we were in the pressed state
                            if (!focusTaken) {
                                //獲取不了焦點川尖,表示正在按下狀態(tài),才處理點擊事件
                                // 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();
                        }
                        
                        //清除 "按下" 狀態(tài)
                        if (prepressed) {
                            postDelayed(mUnsetPressedState,
                                    ViewConfiguration.getPressedStateDuration());
                        } else if (!post(mUnsetPressedState)) {
                            // If the post failed, unpress right now
                            mUnsetPressedState.run();
                        }
                        
                       //取消點擊檢測計時器茫孔。即 "延時按下" 狀態(tài)
                        removeTapCallback();
                    }
                    mIgnoreNextUpEvent = false;
                    break;

                case MotionEvent.ACTION_DOWN:
                    mHasPerformedLongPress = false;
                    
                    //執(zhí)行按鈕的相關(guān)操作
                    //比如菜單欄點擊
                    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.
                    //當父視圖處于滾動中叮喳,則延時處理 "按下" 狀態(tài)
                    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:
                    //當事件取消時候,清理
                    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;
            }
            
            //不管有沒有處理,只要該視圖具有 "可點擊" 剩晴,就會默認消費掉該事件
            //即使該視圖不啟用锣咒,依然會消費事件,只是不執(zhí)行 "點擊" 事件赞弥。
            return true;
        }

        return false;
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末毅整,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子绽左,更是在濱河造成了極大的恐慌悼嫉,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,183評論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件拼窥,死亡現(xiàn)場離奇詭異承粤,居然都是意外死亡,警方通過查閱死者的電腦和手機闯团,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,850評論 3 399
  • 文/潘曉璐 我一進店門辛臊,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人房交,你說我怎么就攤上這事彻舰。” “怎么了候味?”我有些...
    開封第一講書人閱讀 168,766評論 0 361
  • 文/不壞的土叔 我叫張陵刃唤,是天一觀的道長。 經(jīng)常有香客問我白群,道長尚胞,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,854評論 1 299
  • 正文 為了忘掉前任帜慢,我火速辦了婚禮笼裳,結(jié)果婚禮上唯卖,老公的妹妹穿的比我還像新娘。我一直安慰自己躬柬,他們只是感情好拜轨,可當我...
    茶點故事閱讀 68,871評論 6 398
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著允青,像睡著了一般橄碾。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上颠锉,一...
    開封第一講書人閱讀 52,457評論 1 311
  • 那天法牲,我揣著相機與錄音,去河邊找鬼琼掠。 笑死皆串,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的眉枕。 我是一名探鬼主播,決...
    沈念sama閱讀 40,999評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼怜森,長吁一口氣:“原來是場噩夢啊……” “哼速挑!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起副硅,我...
    開封第一講書人閱讀 39,914評論 0 277
  • 序言:老撾萬榮一對情侶失蹤姥宝,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后恐疲,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體腊满,經(jīng)...
    沈念sama閱讀 46,465評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,543評論 3 342
  • 正文 我和宋清朗相戀三年培己,在試婚紗的時候發(fā)現(xiàn)自己被綠了碳蛋。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,675評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡省咨,死狀恐怖肃弟,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情零蓉,我是刑警寧澤笤受,帶...
    沈念sama閱讀 36,354評論 5 351
  • 正文 年R本政府宣布,位于F島的核電站敌蜂,受9級特大地震影響箩兽,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜章喉,卻給世界環(huán)境...
    茶點故事閱讀 42,029評論 3 335
  • 文/蒙蒙 一汗贫、第九天 我趴在偏房一處隱蔽的房頂上張望身坐。 院中可真熱鬧,春花似錦芳绩、人聲如沸掀亥。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,514評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽搪花。三九已至,卻和暖如春嘹害,著一層夾襖步出監(jiān)牢的瞬間撮竿,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,616評論 1 274
  • 我被黑心中介騙來泰國打工笔呀, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留幢踏,地道東北人。 一個月前我還...
    沈念sama閱讀 49,091評論 3 378
  • 正文 我出身青樓许师,卻偏偏與公主長得像房蝉,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子微渠,可洞房花燭夜當晚...
    茶點故事閱讀 45,685評論 2 360

推薦閱讀更多精彩內(nèi)容