Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> View的事件分發機制源碼解析

View的事件分發機制源碼解析

編輯:關於Android編程

 

我們知道當一個點擊事件產生後,它的傳遞過程遵循如下順序:
Activity——>Window——>View
即事件總是先傳遞給Activity,Activity再傳遞給Window,最後Window再傳遞給頂級View。頂級View接受事件後,就會按照事件分發機制去分發事件。

1、Activity對點擊事件的分發過程

點擊事件用MotionEvent來表示,當一個點擊操作發生時,事件最先傳遞給當前的Activity,由Activity的dispatchTouchEvent方法來進行事件派發,具體的工作是由Activity內部的Window來完成的。window會將事件傳遞給decor view,decor view一般就是當前界面的底層容器(即setContentView所設置的View的父容器)通過Activity.getWindow.getDecorView()可以獲得。先從Activity的dispatchTouchEvent開始分析。

Activity#dispatchTouchEvent

 

    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            onUserInteraction();
        }
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

 

從上面的源碼可以看出,事件開始交給Activity所附屬的Window進行分發,如果返回true,整個事件循環就結束了,返回false意味著事件沒人處理。也就是說,當所有View的onTouchEvent方法都返回false時,那麼Activity的onTouchEvent方法會被調用。

2、Window點擊事件的分發過程

接下來看Window是如何將事件傳遞給ViewGroup的。通過源碼可以發現Window是個抽象類,而Window的superDispatchTouchEvent方法也是個抽象方法。因此需要找到Window的實現類才可以。

 

public abstract boolean superDispatchKeyEvent(KeyEvent event);
其實Window的實現類是PhoneWindow,從Window類最上面的注釋可以看出來,如下所示,在第二段中,The only existing implementation of this abstract class isandroid.policy.PhoneWindow。

 

 

/**
 * Abstract base class for a top-level window look and behavior policy.  An
 * instance of this class should be used as the top-level view added to the
 * window manager. It provides standard UI policies such as a background, title
 * area, default key processing, etc.
 *
 * 

The only existing implementation of this abstract class is * android.policy.PhoneWindow, which you should instantiate when needing a * Window. Eventually that class will be refactored and a factory method * added for creating Window instances without knowing about a particular * implementation. */


不過PhoneWindow並不在android.policy包下。

 

實際包名為package com.android.internal.policy.impl;其superDispatchKeyEvent方法源碼如下,
PhoneWindow#superDispatchKeyEvent

 

    @Override
    public boolean superDispatchKeyEvent(KeyEvent event) {
        return mDecor.superDispatchKeyEvent(event);
    }

到這裡邏輯就很清晰了,PhoneWindow將事件直接傳遞給了DecorView,這個DecorView是什麼呢?請看源碼

 

 

private final class DecorView extends FrameLayout implements RootViewSurfaceTaker

DecorView是PhoneWindow中一個內部類,在PhoneWindow中有這樣一句。

 

 

// This is the top-level view of the window, containing the window decor.
    private DecorView mDecor;

 

我們知道,通過getWindow().getDecorView()返回的是一個DecorView,而我們通過setContentView設置的View是DecorView的子View,由於DecorView是繼承FramLayout而且是View的父元素,所以點擊事件一定會傳到View。至於怎麼傳遞的,這裡就不深究了。這裡所裡所說的View是通過setContentView設置的View。這個View是頂級View。根View是DecorView。

 

3、頂級View對點擊事件的分發過程

頂級View一般是一個ViewGroup,當點擊事件到大頂級ViewGroup後,頂級ViewGroup會調用自己的dispatchTouchEvent方法。一級一級往下分發。回顧上一篇博客(對於一個根ViewGroup來說,點擊事件產生後,首先會傳遞給它,這時它的dispaTouchEvent就會被調用,如果這個ViewGroup的onInterceptTouchEvent方法返回true就表示他要攔截當前事件,接著事件就會交給這個ViewGroup處理,即它的onTouchEvent就會被調用,如果這個ViewGroup的onInterceptTouchEvent方法返回false返回false就表示它不攔截這個事件,這時當前事件會繼續傳遞給它的子元素,接著子元素的dispaTouchEvent方法就會被調用,如此反復直到事件被最終處理。)

首先看ViewGroup對點擊事件的分發過程,其主要實現在ViewGroup的dispatchTouchEvent方法中,而這個方法比較長,所以分段說明。先看下面一段。很顯然,它描述的是當前View是否攔截點擊事情這個邏輯。

 

 	    // 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;
            }

從上面的代碼可以看出,ViewGroup在如下兩種情況下會判斷是否攔截當前事件:事件類型為down或者mFirstTouchTarget != null。down這個點擊事件好理解。那麼mFirstTouchTarget != null是什麼意思呢。通過後面的代碼可以看出來,當ViewGroup不攔截事件並將事件交由子元素處理時,mFirstTouchTarget會被賦值也就是mFirstTouchTarget != null。這樣當move事件和up事件到來時,並且事件已經被分發下去,那麼onInterceptTouchEvent這個方法將不會再被調用。

 

 

當然有一種特殊情況,即使事件已經被分發下去,在move核up事件,onInterceptTouchEvent還是會被調用,那就是FLAG_DISALLOW_INTERCEPT標志位。這個表示為是通過ViewGroup的requestDisallowInterceptTouchEvent這個方法來設置的。即使事件已經分發下去,子元素仍然可以調用父元素的requestDisallowInterceptTouchEvent方法來置位FLAG_DISALLOW_INTERCEPT標志位,從而從父元素判斷是否攔截事件。但是down事件除外。因為ViewGroup在分發事件時,如果是down事件就會重置FLAG_DISALLOW_INTERCEPT這個標志位,將導致子View中設置的這個標志位無效。而從上面的代碼,也說明了ViewGroup會根據down事件判斷是否攔截事件。

 

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

接著再看當ViewGroup不攔截事件的時候,事件會向下分發交由它的子View進行處理,這段源碼如下所示。

 

 

		    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 View[] children = mChildren;

                        final boolean customOrder = isChildrenDrawingOrderEnabled();
                        for (int i = childrenCount - 1; i >= 0; i--) {
                            final int childIndex = customOrder ?
                                    getChildDrawingOrder(childrenCount, i) : i;
                            final View child = children[childIndex];
                            if (!canViewReceivePointerEvents(child)
                                    || !isTransformedTouchPointInView(x, y, child, null)) {
                                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();
                                mLastTouchDownIndex = childIndex;
                                mLastTouchDownX = ev.getX();
                                mLastTouchDownY = ev.getY();
                                newTouchTarget = addTouchTarget(child, idBitsToAssign);
                                alreadyDispatchedToNewTouchTarget = true;
                                break;
                            }
                        }

上面這段代碼邏輯也很清晰,首先遍歷ViewGroup的所有子元素,然後判斷子元素是否能夠收到點擊事件。是否能夠收到點擊事件主要由兩點來衡量:子元素是否在播放動畫和點擊事件的坐標是否落在子元素的區域內。如果某個子元素滿足這兩個條件,那麼事件就會傳遞給它處理,dispatchTransformedTouchEvent這個方法實際上就是調用子元素的dispatchTouchEvent方法,在它的內部有如下一段內容,如下所示,由於上面傳遞child不是null,因此它會直接調用子元素的dispatchTouchEvent方法,這樣事件就交由子元素處理,從而完成了一輪事件分發。

 

 

            if (child == null) {
                handled = super.dispatchTouchEvent(event);
            } else {
                handled = child.dispatchTouchEvent(event);
            }
如果子元素的dispatchTouchEvent返回true,表示子元素已經處理完事件,那麼mFirstTouchTarget就會被賦值同時跳出for循環,如下所示:

 

 

                                newTouchTarget = addTouchTarget(child, idBitsToAssign);
                                alreadyDispatchedToNewTouchTarget = true;
                                break;
mFirstTouchTarget的賦值在addTouchTarget內部完成,可以看出mFirstTouchTarget是一種單鏈表結構。這裡賦值那麼mFirstTouchTarget != null成立。

 

 

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

如果遍歷完所有的子元素事件沒有被合適處理,有兩種情況,

 

1)ViewGroup沒有子元素

2)子元素處理了點擊事件,但是dispatchTouchEvent返回false
這是ViewGroup會自己處理點擊事件。

在ViewGroup的dispatchTouchEvent方法中,有下面一段代碼:

 

            // 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);
            }

注意這裡的第三個參數child為null,那麼根據上面的分析,此時會調用handled = super.dispatchTouchEvent(event);
            if (child == null) {
                handled = super.dispatchTouchEvent(event);
            } else {
                handled = child.dispatchTouchEvent(event);
            }

很顯然,ViewGroup沒有自己處理事件,而是交給了父類,ViewGroup繼承自View,這樣就轉到了View的dispatchTouchEvent方法,即點擊事件開始交由View來處理。

4、View對點擊事件的分發過程
View對點擊事件的處理過程稍微簡單一些,注意這裡的View不包含ViewGroup。先看它的dispatchTouchEvent方法,如下所示:

 

 

    public boolean dispatchTouchEvent(MotionEvent event) {
        if (mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
        }

        if (onFilterTouchEventForSecurity(event)) {
            //noinspection SimplifiableIfStatement
            ListenerInfo li = mListenerInfo;
            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
                    && li.mOnTouchListener.onTouch(this, event)) {
                return true;
            }

            if (onTouchEvent(event)) {
                return true;
            }
        }

        if (mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
        }
        return false;
    }

View對點擊事件的處理過程就比較簡單了,因為View是一個單獨的元素,它沒有子元素因此無法向下傳遞事件,所以它只能自己處理事件,所以View的onTouchEvent方法默認返回true。

 

從上面的源碼可以看出View對點擊事件的處理過程,首先會判斷有沒有設置OnTouchListener,如果OnTouchListener中的onTouch方法返回true,那麼onTouchEvent方法就不會被調用,可以OnTouchListener的優先級要高於onTouchEvent,這樣做的好處是方便子啊外界處理點擊點擊事件。這也證明上一篇博客中的結論。

接著再分析onTouchEvent的實現,方法內容有點長,先看當View處於不可用狀態下點擊事件的處理過程。也就方法一開始。不可用狀態下還是消耗了點擊事件。

 

        if ((viewFlags & ENABLED_MASK) == DISABLED) {
            if (event.getAction() == 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));
        }


 

下面看一下onTouchEvent對點擊事件的具體處理,如下所示。

 

if (((viewFlags & CLICKABLE) == CLICKABLE ||
                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
            switch (event.getAction()) {
                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);
                       }

                        if (!mHasPerformedLongPress) {
                            // 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();
                    }
                    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();
                        }
                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
                    } else {
                        // Not inside a scrolling container, so show the feedback right away
                        setPressed(true);
                        checkForLongClick(0);
                    }
                    break;

                case MotionEvent.ACTION_CANCEL:
                    setPressed(false);
                    removeTapCallback();
                    removeLongPressCallback();
                    break;

                case MotionEvent.ACTION_MOVE:
                    final int x = (int) event.getX();
                    final int y = (int) event.getY();

                    // 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;
    }

至此,onTouchEvent方法沒有了,可以看出只要CLICKABLE和LONG_CLICKABLE有一個為true,那麼它就會消耗這個事件,因為返回了true,這個結果用eclipse很容易看出來,這個博客其實不容易看清楚代碼結構,這也證明上一篇博客中的結論。當up事件發生時,會觸發performClick方法,

 

 

                                if (mPerformClick == null) {
                                    mPerformClick = new PerformClick();
                                }
                                if (!post(mPerformClick)) {
                                    performClick();
                                }

 

如果View設置OnClickListener,那麼performClick就會調用它的onClick方法。

 

    public boolean performClick() {
        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);

        ListenerInfo li = mListenerInfo;
        if (li != null && li.mOnClickListener != null) {
            playSoundEffect(SoundEffectConstants.CLICK);
            li.mOnClickListener.onClick(this);
            return true;
        }

        return false;
    }
View的LONG_CLICKABLE屬性默認為false,而CLICKABLE屬性默認為true,不過具體的View的CLICKABLE又不一定,確切來說是可點擊的View其CLICKABLE屬性true,比如Botton,不可點擊的View的CLICKABLE為false,比如TextView。。通過setClickable和setLongClickable可以設置這兩個屬性。另外setOnClickListener和setOnLongClickListener會自動將View的這兩個屬性設為true。這一點從源碼可以看出來。

 

 

    public void setOnClickListener(OnClickListener l) {
        if (!isClickable()) {
            setClickable(true);
        }
        getListenerInfo().mOnClickListener = l;
    }

    public void setOnLongClickListener(OnLongClickListener l) {
        if (!isLongClickable()) {
            setLongClickable(true);
        }
        getListenerInfo().mOnLongClickListener = l;
    }

最後總結一下,這篇博客主要從源碼角度分析View的事件分發機制。一般過程如下。

 

Activity——>PhoneWindow——>DecorView——>ViewGroup——>View

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved