Android 事件分發機制

1、基礎
  1. 事件分發對象:點擊事件(Touch 事件)。
  2. 事件定義:觸摸屏幕,將產生點擊事件。Touch 事件的細節(觸摸時間、位置等)被封裝成 MotionEvent 對象。
  3. 事件類型:
事件類型 具體動作
MotionEvent.ACTION_DOWN 按下
MotionEvent.ACTION_UP 擡起
MotionEvent.ACTION_MOVE 滑動
MotionEvent.ACTION_CANCEL 取消事件(非人爲原因)
  1. 事件類:觸摸屏幕至離開屏幕,產生的一系列事件。
    在這裏插入圖片描述
  2. 事件分發本質:將事件(MotionEvent)傳遞給某個 View 處理的過程。
  3. 事件分發順序:Activity->ViewGroup->View。
  4. 事件分發主要方法
方法 作用
dispatchTouchEvent() 分發事件
onTouchEvent() 處理點擊事件
onInterceptTouchEvent() 攔截事件(ViewGroup 獨有)
2、源碼分析
  1. Activity 事件分發機制
    在這裏插入圖片描述
	Activity.java
	
    public boolean dispatchTouchEvent(MotionEvent ev) {
    	// DOWN 事件 
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            onUserInteraction(); // -> 分析 1
        }
        // getWindow().superDispatchTouchEvent(ev) 返回 true,方法結束,否則執行 onTouchEvent(ev)。-> 分析 2
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);-> 分析 4
    }
    
	// 分析 1:onUserInteraction()
	// 作用:實現屏保功能
	// activity 在棧頂時,觸發 home,back,menu 事件等會觸發該方法。
    public void onUserInteraction() {
    }
	
	// 分析 4:onTouchEvent(ev)
	// 當一個事件未被 activity 下任意 view 接收處理。
	// 點擊事件在Window邊界外才會返回true,默認都返回 false。
    public boolean onTouchEvent(MotionEvent event) {
    	// ->分析 5
        if (mWindow.shouldCloseOnTouch(this, event)) {
            finish();
            return true;
        }

        return false;
    }
	PhoneWindow.java
	
	// 分析 2:getWindow().superDispatchTouchEvent(ev)
	// getWindow() 爲  Window 對象。指向唯一實現類 PhoneWindow 對象。
    @Override
    public boolean superDispatchTouchEvent(MotionEvent event) {
        return mDecor.superDispatchTouchEvent(event);// ->分析 3
    }
	DecorView.java
	
	// 分析 3:mDecor.superDispatchTouchEvent(event)
	// mDecor 爲 DecorView(頂級view)
	// DecorView 繼承 FrameLayout,FrameLayout 繼承 ViewGroup。
	// 將事件傳遞給 ViewGroup 處理,Activity->ViewGroup。
    public boolean superDispatchTouchEvent(MotionEvent event) {
        return super.dispatchTouchEvent(event);
    }
	Window.java

	// 分析 5:mWindow.shouldCloseOnTouch(this, event)
	// 判斷事件在邊界外
    public boolean shouldCloseOnTouch(Context context, MotionEvent event) {
        final boolean isOutside =
                event.getAction() == MotionEvent.ACTION_DOWN && isOutOfBounds(context, event)
                || event.getAction() == MotionEvent.ACTION_OUTSIDE;
        if (mCloseOnTouchOutside && peekDecorView() != null && isOutside) {
            return true;
        }
        return false;
    }
  1. ViewGroup 事件分發機制
    在這裏插入圖片描述
	ViewGroup.java
	
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
     		。。。
            // Check for interception.
            final boolean intercepted;
            if (actionMasked == MotionEvent.ACTION_DOWN
                    || mFirstTouchTarget != null) {
                 // 1、disallowIntercept 是否禁用攔截,默認 false 不禁用,可以通過 requestDisallowInterceptTouchEvent(boolean disallowIntercept) 修改。
                final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
                if (!disallowIntercept) {
                	// 2、disallowIntercept 爲 false沒禁用攔截,調用onInterceptTouchEvent(ev) 攔截事件。
                    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;
            }
			。。。
            // 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 = buildTouchDispatchChildList();
                        final boolean customOrder = preorderedList == null
                                && isChildrenDrawingOrderEnabled();
                        final View[] children = mChildren;
                        // 3、遍歷子view,找到被點擊的view。
                        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;
                            }

                            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.
            //  4、事件分發到子view。->分析 1
            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;
                        }
						。。。
            }
		。。。
        return handled;
    }
	
	// 攔截事件
    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;
    }

	// 分析1:dispatchTransformedTouchEvent
	// 無子view接收事件 或者 攔截事件執行 super.dispatchTouchEvent(transformedEvent)->View.dispatchTouchEvent()->onTouch()->onTouchEvent()->performClick()->onClick()。
	// 否則事件分發到子view(child.dispatchTouchEvent(transformedEvent)):ViewGroup->View
    private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
            View child, int desiredPointerIdBits) {
       。。。
        // 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;
    }
    
  1. View 事件分發機制
    在這裏插入圖片描述
    public boolean dispatchTouchEvent(MotionEvent event) {
      	。。。
            // 1、mOnTouchListener != null;2、(mViewFlags & ENABLED_MASK) == ENABLED;3、mOnTouchListener.onTouch(this, event))。result = true 及 dispatchTouchEvent 返回true;否則執行onTouchEvent()。
            if (li != null && li.mOnTouchListener != null
                    && (mViewFlags & ENABLED_MASK) == ENABLED
                    && li.mOnTouchListener.onTouch(this, event)) {
                result = true;
            }
			// onTouchEvent(event) ->分析 1
            if (!result && onTouchEvent(event)) {
                result = true;
            }
        }
		。。。
        return result;
    }

	// 分析 1 :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;
            }
        }
		// 1、view 可點擊
        if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
            switch (action) {
            	// 擡起事件
                case MotionEvent.ACTION_UP:
                   			。。。
                   			// 執行performClick()->分析 1
                            performClick();
                            。。。
                    break;
                // 按下事件
                case MotionEvent.ACTION_DOWN:
               		 。。。
                    break;
				// 事件取消
                case MotionEvent.ACTION_CANCEL:
            		。。。
                    break;
				 // 滑動事件
                case MotionEvent.ACTION_MOVE:
             		。。。
                    break;
            }
            // 控件可點擊,返回 true。
            return true;
        }
 		// 控件不可點擊,返回 false。
        return false;
    }
	
	// 分析 1:performClick()
	// 控件註冊點擊事件執行 onClick(),返回 true。
	// 沒註冊點擊事件,返回 false。
    public boolean performClick() {
        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;
        }
		。。。
        return result;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章