Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發 >> 關於android開發 >> 深入透析Android事件分發機制

深入透析Android事件分發機制

編輯:關於android開發

深入透析Android事件分發機制


一、 Android分發機制概述:

  Android如此受歡迎,就在於其優秀的交互性,這其中,Android優秀的事件分發機制功不可沒。那麼,作為一個優秀的程序員,要想做一個具有良好交互性的應用,必須透徹理解Android的事件分發機制。

  要想充分理解android的分發機制,需要先對以下幾個知識點有所了解:

① View和ViewGroup什麼?

② 事件

③ View 事件的分發機制

④ ViewGroup事件的分發機制

  下面,就讓我們沿著大致方向,開始事件分發的探究之旅吧……

二、 View和ViewGroup:

  Android的UI界面都是由View和ViewGroup及其派生類組合而成的。其中,View是所有UI組件的基類,而ViewGroup是容納這些組件的容器,其本身也是從View派生出來的,也就是說ViewGroup的父類就是View。

  通常來說,Button、ImageView、TextView等控件都是繼承父類View來實現的。RelativeLayout、LinearLayout、FrameLayout等布局都是繼承父類ViewGroup來實現的。

三、事件:

  當手指觸摸到View或ViewGroup派生的控件後,將會觸發一系列的觸發響應事件,如:

  onTouchEvent、onClick、onLongClick等。每個View都有自己處理事件的回調方法,開發人員只需要重寫這些回調方法,就可以實現需要的響應事件。

  而事件通常重要的有如下三種:

  MotionEvent.ACTION_DOWN 按下View,是所有事件的開始

  MotionEvent.ACTION_MOVE 滑動事件

  MotionEvent.ACTION_UP 與down對應,表示抬起

  事件的響應原理:

  在android開發設計模式中,最廣泛應用的就是監聽、回調,進而形成了事件響應的過程。

  以Button的OnClick為例,因為Button也是一個View,所以它也擁有View父類的方法,在View中源碼如下:
/**定義接口成員變量*/

protected OnClickListener mOnClickListener;

    /**

     * Interface definition for a callback to be invoked when a view is clicked.

     */

    public interface OnClickListener {

        /**

         * Called when a view has been clicked.

         *

         * @param v The view that was clicked.

         */

        void onClick(View v);

    }

/**

     * Register a callback to be invoked when this view is clicked. If this view is not

     * clickable, it becomes clickable.

     *

     * @param l The callback that will run

     *

     * @see #setClickable(boolean)

     */

    public void setOnClickListener(OnClickListener l) {

        if (!isClickable()) {

            setClickable(true);

        }

        mOnClickListener = l;

}



/**

     * Call this view's OnClickListener, if it is defined.

     *

     * @return True there was an assigned OnClickListener that was called, false

     *         otherwise is returned.

     */

    public boolean performClick() {

        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);



        if (mOnClickListener != null) {

            playSoundEffect(SoundEffectConstants.CLICK);

            mOnClickListener.onClick(this);

            return true;

        }



        return false;

}

/**觸摸了屏幕後,實現並調用的方法*/

public boolean onTouchEvent(MotionEvent event) {

           …..

                   if (mPerformClick == null) {

                                    mPerformClick = new PerformClick();

                                }

                                if (!post(mPerformClick)) {

                                    performClick();

                                }

           …..

}

以上是View源碼中關鍵代碼行,以Button為例,假設需要在一個布局上添加一個按鈕,並實現它的OnClick事件,需要如下步驟:

1、 OnClickListener類是一個當控件被點擊後進行回調的一個接口,它完成被點擊後的回調通知。

2、 創建一個按鈕Button,並設置監聽事件,對這個Button進行setOnClickListener操作

3、 當手指觸摸到Button按鈕,通過一系列方法(之後將會詳細講解,這裡暫時忽略),觸發並執行到onTouchEvent方法並執行mPerformClick方法,在mPerformClick方法中,首先會判斷注 冊的mOnClickListener是否為空,若不為空,它就會回調之前注冊的onClick方法,進而執行用戶自定義代碼。

  事件響應機制,簡單來說上面的例子就已經基本上诠釋了

  注冊一個監聽對象

  實現監聽對象的監聽事件

  當某一觸發事件到來,在觸發事件中通過注冊過的監聽對象,回調注冊對象的響應事件,來完成用戶自定義實現。

但凡明白了這一個簡單的事件響應的過程,就離事件驅動開發整個過程就不遠了,大道至簡,請完全理解了這個例子,再繼續之後的學習,事半功倍。

四、 View事件的分發機制:

  通過上面的例子,我們初步的接觸了View的事件分發機制,再進一步了解。首先,我們要熟悉dispatchTouchEvent和onTouchEvent兩個函數,這兩個函數都是View的函數,要理解View事件的分發機制,只要清楚這兩個函數就基本上清楚了。

在這裡先提醒一句,這裡的“分發”是指一個觸摸或點擊的事件發生,分發給當前觸摸控件所監聽的事件(如OnClick、onTouch等),進而來決定是控件的哪個函數來響應此次事件。

dispatchTouchEvent:

  此函數負責事件的分發,你只需要記住當觸摸一個View控件,首先會調用這個函數就行,在這個函數體裡決定將事件分發給誰來處理。

onTouchEvent:

  此函數負責執行事件的處理,負責處理事件,主要處理MotionEvent.ACTION_DOWN、

MotionEvent.ACTION_MOVE 、MotionEvent.ACTION_UP這三個事件。

  public boolean onTouchEvent (MotionEvent event) 

  參數event為手機屏幕觸摸事件封裝類的對象,其中封裝了該事件的所有信息,例如觸摸的位置、觸摸的類型以及觸摸的時間等。該對象會在用戶觸摸手機屏幕時被創建。

那麼它是如何執行這個流程的呢?我們還以布局上的按鈕為例,看看它是如何實現的。(看圖①)
這裡寫圖片描述
我們知道,View做為所有控件的父類,它本身定義了很多接口來監聽觸摸在View上的事件,如OnClickListener(點擊)、OnLongClickListener(長按)、OnTouchListener(觸摸監聽)等,那麼當手指觸摸到View時候,該響應“點擊”還是”觸摸”呢,就是根據dispatchTouchEvent和onTouchEvent這兩個函數組合實現的,我們之下的討論,僅對常用的“點擊OnClick”和“觸摸onTouch”來討論,順籐摸瓜,找出主線,進而搞清楚View的事件分發機制。

  對於上面的按鈕,點擊它一下,我們期望2種結果,第一種:它響應一個點擊事件。第二種:不響應點擊事件。

第一種源碼:

public class MainActivity extends Activity implements OnClickListener ,OnTouchListener{

  private Button btnButton;

  @Override

  protected void onCreate(Bundle savedInstanceState) {

       super.onCreate(savedInstanceState);

       setContentView(R.layout.activity_main);

       btnButton=(Button) findViewById(R.id.btn);

       btnButton.setOnClickListener(this);

       btnButton.setOnTouchListener(this);

       }



  @Override

  public void onClick(View v) {

       // TODO Auto-generated method stub

       switch (v.getId()) {

       case R.id.btn:

             Log.e(View, onClick===========>);

             break;

       default:

             break;

       }

  }



  @Override

  public boolean onTouch(View v, MotionEvent event) {

       // TODO Auto-generated method stub

       Log.e(View, onTouch..................................);

       return false;

  }

}

這裡寫圖片描述

第二種源碼:

public class MainActivity extends Activity implements OnClickListener ,OnTouchListener{

  private Button btnButton;

  @Override

  protected void onCreate(Bundle savedInstanceState) {

       super.onCreate(savedInstanceState);

       setContentView(R.layout.activity_main);

       btnButton=(Button) findViewById(R.id.btn);

       btnButton.setOnClickListener(this);

       btnButton.setOnTouchListener(this);

       }



  @Override

  public void onClick(View v) {

       // TODO Auto-generated method stub

       switch (v.getId()) {

       case R.id.btn:

             Log.e(View, onClick===========>);

             break;

       default:

             break;

       }

  }



  @Override

  public boolean onTouch(View v, MotionEvent event) {

       // TODO Auto-generated method stub

       Log.e(View, onTouch..................................);

       return true;

  }

}

這裡寫圖片描述

結果分析:

  上面兩處代碼,第一種執行了OnClick函數和OnTouch函數,第二種執行了OnTouch函數,並沒有執行OnClick函數,而且對兩處代碼進行比較,發現只有在onTouch處返回值true和false不同。當onTouch返回false,onClick被執行了,返回true,onClick未被執行。

  為什麼會這樣呢?我們只有深入源碼才能分析出來。

  前面提到,觸摸一個View就會執行dispatchTouchEvent方法去“分發”事件,  既然觸摸的是按鈕Button,那麼我們就查看Button的源碼,尋找dispatchTouchEvent方法,Button源碼中沒有dispatchTouchEvent方法,但知道Button繼承自TextView,尋找TextView,發現它也沒有dispatchTouchEvent方法,繼續查找TextView的父類View,發現View有dispatchTouchEvent方法,那我們就分析dispatchTouchEvent方法。

主要代碼如下:

public boolean dispatchTouchEvent(MotionEvent event) {

        if (onFilterTouchEventForSecurity(event)) {

            //noinspection SimplifiableIfStatement

            if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED &&

                    mOnTouchListener.onTouch(this, event)) {

                return true;

            }



            if (onTouchEvent(event)) {

                return true;

            }

        }

        return false;

}

分析:

先來看dispatchTouchEvent函數返回值,如果返回true,表明事件被處理了,反之,表明事件未被處理。

public boolean dispatchTouchEvent(MotionEvent event) {

        if (onFilterTouchEventForSecurity(event)) {

            //noinspection SimplifiableIfStatement

            if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED &&

                    mOnTouchListener.onTouch(this, event)) {

                return true;

            }



            if (onTouchEvent(event)) {

                return true;

            }

        }

        return false;

}

這個判定很重要,mOnTouchListener != null,判斷該控件是否注冊了OnTouchListener對象的監聽,(mViewFlags & ENABLED_MASK) == ENABLED,判斷當前的控件是否能被點擊(比如Button默認可以點擊,ImageView默認不許點擊,看到這裡就了然了),mOnTouchListener.onTouch(this, event)這個是關鍵,這個調用,就是回調你注冊在這個View上的mOnTouchListener對象的onTouch方法,如果你在onTouch方法裡返回false,那麼這個判斷語句就跳出,去執行下面的程序,否則,當前2個都返回了true,自定義onTouch方法也返回true,條件成立,就直接返回了,不再執行下面的程序。接下來,if (onTouchEvent(event)) 這個判斷很重要,能否回調OnClickListener接口的onClick函數,關鍵在於此,可以肯定的是,如果上面if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED &&

                mOnTouchListener.onTouch(this, event))返回true,那麼就不會執行並回調OnClickListener接口的onClick函數。

  接下來,我們看onTouchEvent這個函數,看它是如何響應點擊事件的。

  主要代碼如下:
public boolean onTouchEvent(MotionEvent event) {

        final int viewFlags = mViewFlags;



        if ((viewFlags & ENABLED_MASK) == DISABLED) {

            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PRESSED) != 0) {

                mPrivateFlags &= ~PRESSED;

                refreshDrawableState();

            }

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

        }



        if (mTouchDelegate != null) {

            if (mTouchDelegate.onTouchEvent(event)) {

                return true;

            }

        }



        if (((viewFlags & CLICKABLE) == CLICKABLE ||

                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {

            switch (event.getAction()) {

                case MotionEvent.ACTION_UP:

                    boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;

                    if ((mPrivateFlags & 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.

                            mPrivateFlags |= PRESSED;

                            refreshDrawableState();

                       }



                        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 |= PREPRESSED;

                        if (mPendingCheckForTap == null) {

                            mPendingCheckForTap = new CheckForTap();

                        }

                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());

                    } else {

                        // Not inside a scrolling container, so show the feedback right away

                        mPrivateFlags |= PRESSED;

                        refreshDrawableState();

                        checkForLongClick(0);

                    }

                    break;



                case MotionEvent.ACTION_CANCEL:

                    mPrivateFlags &= ~PRESSED;

                    refreshDrawableState();

                    removeTapCallback();

                    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 & PRESSED) != 0) {

                            // Remove any future long press/tap checks

                            removeLongPressCallback();



                            // Need to switch from pressed to not pressed

                            mPrivateFlags &= ~PRESSED;

                            refreshDrawableState();

                        }

                    }

                    break;

            }

            return true;

        }



        return false;

}

    public boolean performClick() {

        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);



        if (mOnClickListener != null) {

            playSoundEffect(SoundEffectConstants.CLICK);

            mOnClickListener.onClick(this);

            return true;

        }



        return false;

    }

代碼量太大了,不過不要緊,我們通過主要代碼分析一下。

public boolean onTouchEvent(MotionEvent event) {



        //控件不能被點擊

        if ((viewFlags & ENABLED_MASK) == DISABLED) {

             …

        }

//委托代理別的View去實現

        if (mTouchDelegate != null) {

            if (mTouchDelegate.onTouchEvent(event)) {

                return true;

            }

        }

        //控件能夠點擊或者長按

        if (((viewFlags & CLICKABLE) == CLICKABLE ||

                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {

            switch (event.getAction()) {

            //抬起事件

                case MotionEvent.ACTION_UP:

                          …...

                            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)) {

                        //這裡就是去執行回調注冊的onClick函數,實現點擊

                                    performClick();

                                }

                            }

                            ……

                    break;

           //按下事件

                case MotionEvent.ACTION_DOWN:



                    ……

                    break;



               ……

           //移動事件

                case MotionEvent.ACTION_MOVE:

                     ……

                    break;

            }



            return true;

        }
        return false;

}

從上面主要代碼可以看出onTouchEvent傳參MotionEvent類型,它封裝了觸摸的活動事件,其中就有MotionEvent.ACTION_DOWN、MotionEvent.ACTION_MOVE、MotionEvent.ACTION_UP三個事件。我們在來看看onTouchEvent的返回值,因為onTouchEvent是在dispatchTouchEvent事件分發處理中調用的,

public boolean dispatchTouchEvent(MotionEvent event) {

         ……

            if (onTouchEvent(event)) {

                return true;

            }

return fasle;

        }

如果onTouchEvent返回true,dispatchTouchEvent就返回true,表明事件被處理了,反之,事件未被處理。

程序的關鍵在 if (((viewFlags & CLICKABLE) == CLICKABLE ||

            (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE))的判斷裡,我們發現無論switch的分支在什麼地方跳出,返回都是true。這就表明,無論是三個事件中的哪一個,都會返回true。

  參照下圖,結合上述,不難理解View的分發機制了。

這裡寫圖片描述

四、 ViewGroup事件分發機制:

  ViewGroup事件分發機制較View的稍微復雜一些,不過對View的機制只要精確的理解後,仔細看過這一節,睡幾覺起來,估計也就悟出來了,學習就是這麼奇怪,當下理解不了或模糊的地方,只要腦子有印象,忽然一夜好像就懂了。

  先來看下面的一個簡單布局,我們將通過例子,了解ViewGroup+View的android事件處理機制。

這裡寫圖片描述

上圖由:黑色為線性布局LinearLayout,紫色為相對布局RelativeLayout,按鈕Button三部分組成。RelativeLayout為LinearLayout的子布局,Button為RelativeLayout的子布局。以下RelativeLayout簡稱(R),LinearLayout簡稱(L),Button簡稱(B)。<喎?http://www.Bkjia.com/kf/ware/vc/" target="_blank" class="keylink">vcD4NCjxwcmUgY2xhc3M9"brush:java;"> 經過前面講解,我們首先知道這樣兩件事情。

1、(R)和(L)的父類是ViewGroup,(B)的父類是View。

2、dispatchTouchEvent這個函數很重要,不論是ViewGroup還是View,都由它來處理事件的消費和傳遞。

  下面,我們通過橫向和縱向兩個維度,通過源碼和圖解的方式,充分理解事件的傳遞機制。

  先來看整體的事件傳遞過程:

這裡寫圖片描述

當手指點擊按鈕B時,事件傳遞的順序是從底向上傳遞的,也就是按照L->R->B的順序由下往上逐層傳遞,響應正好相反,是自上而下。

  L首先接收到點擊事件,L的父類是ViewGroup類,並將事件傳遞給dispatchTouchEvent方法,dispatchTouchEvent函數中判斷該控件L是否重載了onInterceptTouchEvent方法進行事件攔截,onInterceptTouchEvent默認返回false不攔截,那麼dispatchTouchEvent方法將事件傳遞給R去處理(進入第2流程處理),如果返回true表示當前L控件攔截了事件向其它控件的傳遞,交給它自己父類View的dispatchTouchEvent去處理,在父方法的dispatchTouchEvent中,將會按照前面講的View的事件處理機制去判斷,比如判斷L是否重載了onTouch方法,是否可點擊,是否做了監聽等事件。

  R也是ViewGroup的子類,因此與第1流程基本相似,如果onInterceptTouchEvent返回了false,表示事件將不攔截繼續傳遞給B。

  B是View的子類,它沒有onInterceptTouchEvent方法,直接交給自己父類View的dispatchTouchEvent去處理,流程同不再敷述。

  總結:

  onInterceptTouchEvent只有ViewGroup才有,當一個控件是繼承自ViewGroup而來的,那麼它就可能會有子控件,因此,才有可能傳遞給子控件,而繼承自View的控件,不會有子控件,也就沒有onInterceptTouchEvent函數了。

  通過dispatchTouchEvent分發的控件返回值True和false,表示當前控件是否消費了傳遞過來的事件,如果消費了,返回True,反之false。消費了,就不再繼續傳遞了,沒有消費,如果有子控件將繼續傳遞。

  啰嗦點,如果想再深層次了解一下,再次從源碼ViewGroup來分析一個L控件的事件傳遞過程,請看下圖:

這裡寫圖片描述

結合上面的圖例,下面列出ViewGroup源碼來分析一下,我們只需要分析ViewGroup的dispatchTouchEvent、onInterceptTouchEvent、dispatchTransformedTouchEvent三個方法即可。

public boolean dispatchTouchEvent(MotionEvent ev) {

        if (mInputEventConsistencyVerifier != null) {

            mInputEventConsistencyVerifier.onTouchEvent(ev, 1);

        }



        boolean handled = false;

        if (onFilterTouchEventForSecurity(ev)) {

            final int action = ev.getAction();

            final int actionMasked = action & MotionEvent.ACTION_MASK;



            // Handle an initial down.

            if (actionMasked == MotionEvent.ACTION_DOWN) {

                // Throw away all previous state when starting a new touch gesture.

                // The framework may have dropped the up or cancel event for the previous gesture

                // due to an app switch, ANR, or some other state change.

                cancelAndClearTouchTargets(ev);

                resetTouchState();

            }



            // Check for interception.

            final boolean intercepted;

            if (actionMasked == MotionEvent.ACTION_DOWN

                    || mFirstTouchTarget != null) {

                final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;

                if (!disallowIntercept) {

                    intercepted = onInterceptTouchEvent(ev);

                    ev.setAction(action); // restore action in case it was changed

                } else {

                    intercepted = false;

                }

            } else {

                // There are no touch targets and this action is not an initial down

                // so this view group continues to intercept touches.

                intercepted = true;

            }



            // 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 (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 (childrenCount != 0) {

                        // Find a child that can receive the event.

                        // Scan children from front to back.

                        final View[] children = mChildren;

                        final float x = ev.getX(actionIndex);

                        final float y = ev.getY(actionIndex);



                        for (int i = childrenCount - 1; i >= 0; i--) {

                            final View child = children[i];

                            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 = i;

                                mLastTouchDownX = ev.getX();

                                mLastTouchDownY = ev.getY();

                                newTouchTarget = addTouchTarget(child, idBitsToAssign);

                                alreadyDispatchedToNewTouchTarget = true;

                                break;

                            }

                        }

                    }



                    if (newTouchTarget == null && mFirstTouchTarget != null) {

                        // Did not find a child to receive the event.

                        // Assign the pointer to the least recently added target.

                        newTouchTarget = mFirstTouchTarget;

                        while (newTouchTarget.next != null) {

                            newTouchTarget = newTouchTarget.next;

                        }

                        newTouchTarget.pointerIdBits |= idBitsToAssign;

                    }

                }

            }



            // Dispatch to touch targets.

            if (mFirstTouchTarget == null) {

                // No touch targets so treat this as an ordinary view.

                handled = dispatchTransformedTouchEvent(ev, canceled, null,

                        TouchTarget.ALL_POINTER_IDS);

            } else {

                // Dispatch to touch targets, excluding the new touch target if we already

                // dispatched to it.  Cancel touch targets if necessary.

                TouchTarget predecessor = null;

                TouchTarget target = mFirstTouchTarget;

                while (target != null) {

                    final TouchTarget next = target.next;

                    if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {

                        handled = true;

                    } else {

                        final boolean cancelChild = resetCancelNextUpFlag(target.child)

                        || intercepted;

                        if (dispatchTransformedTouchEvent(ev, cancelChild,

                                target.child, target.pointerIdBits)) {

                            handled = true;

                        }

                        if (cancelChild) {

                            if (predecessor == null) {

                                mFirstTouchTarget = next;

                            } else {

                                predecessor.next = next;

                            }

                            target.recycle();

                            target = next;

                            continue;

                        }

                    }

                    predecessor = target;

                    target = next;

                }

            }



            // Update list of touch targets for pointer up or cancel, if needed.

            if (canceled

                    || actionMasked == MotionEvent.ACTION_UP

                    || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {

                resetTouchState();

            } else if (split && actionMasked == MotionEvent.ACTION_POINTER_UP) {

                final int actionIndex = ev.getActionIndex();

                final int idBitsToRemove = 1 << ev.getPointerId(actionIndex);

                removePointersFromTouchTargets(idBitsToRemove);

            }

        }



        if (!handled && mInputEventConsistencyVerifier != null) {

            mInputEventConsistencyVerifier.onUnhandledEvent(ev, 1);

        }

        return handled;

}

  public boolean onInterceptTouchEvent(MotionEvent ev) {

        return false;

    }

  private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,

            View child, int desiredPointerIdBits) {

        final boolean handled;



        // Canceling motions is a special case.  We don't need to perform any transformations

        // or filtering.  The important part is the action, not the contents.

        final int oldAction = event.getAction();

        if (cancel || oldAction == MotionEvent.ACTION_CANCEL) {

            event.setAction(MotionEvent.ACTION_CANCEL);

            if (child == null) {

                handled = super.dispatchTouchEvent(event);

            } else {

                handled = child.dispatchTouchEvent(event);

            }

            event.setAction(oldAction);

            return handled;

        }



        // Calculate the number of pointers to deliver.

        final int oldPointerIdBits = event.getPointerIdBits();

        final int newPointerIdBits = oldPointerIdBits & desiredPointerIdBits;



        // If for some reason we ended up in an inconsistent state where it looks like we

        // might produce a motion event with no pointers in it, then drop the event.

        if (newPointerIdBits == 0) {

            return false;

        }



        // If the number of pointers is the same and we don't need to perform any fancy

        // irreversible transformations, then we can reuse the motion event for this

        // dispatch as long as we are careful to revert any changes we make.

        // Otherwise we need to make a copy.

        final MotionEvent transformedEvent;

        if (newPointerIdBits == oldPointerIdBits) {

            if (child == null || child.hasIdentityMatrix()) {

                if (child == null) {

                    handled = super.dispatchTouchEvent(event);

                } else {

                    final float offsetX = mScrollX - child.mLeft;

                    final float offsetY = mScrollY - child.mTop;

                    event.offsetLocation(offsetX, offsetY);



                    handled = child.dispatchTouchEvent(event);



                    event.offsetLocation(-offsetX, -offsetY);

                }

                return handled;

            }

            transformedEvent = MotionEvent.obtain(event);

        } else {

            transformedEvent = event.split(newPointerIdBits);

        }



        // Perform any necessary transformations and dispatch.

        if (child == null) {

            handled = super.dispatchTouchEvent(transformedEvent);

        } else {

            final float offsetX = mScrollX - child.mLeft;

            final float offsetY = mScrollY - child.mTop;

            transformedEvent.offsetLocation(offsetX, offsetY);

            if (! child.hasIdentityMatrix()) {

                transformedEvent.transform(child.getInverseMatrix());

            }



            handled = child.dispatchTouchEvent(transformedEvent);

        }



        // Done.

        transformedEvent.recycle();

        return handled;

    }

代碼量比較大,我們先概述一下各個函數的主要作用。

  dispatchTouchEvent主要用來分發事件,函數主要作用是來決定當前的事件是交由自己消費處理,還是交由子控件處理。

  onInterceptTouchEvent主要來決定當前控件是否需要攔截傳遞給子控件,如果返回True表示該控件攔截,並交由自己父類的dispatchTouchEvent處理消費,如果返回false表示不攔截,允許傳遞給子控件處理。

  dispatchTransformedTouchEvent主要根據傳來的子控件,決定是自身處理消費,還是交由子控件處理消費。

我們主要來分析一下dispatchTouchEvent函數:

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;

            }

這段代碼,如果當前傳遞的事件是Down(按下)或者當前觸摸鏈表不為空,那麼它調用onInterceptTouchEvent函數,判斷是否進行事件攔截處理,通過返回值來決定intercepted變量的值。

接下來if (!canceled && !intercepted){} 這個括號內的代碼需要注意了,只有當intercepted返回值為false的時候,才滿足這個條件進入代碼段。因此,我們結合onInterceptTouchEvent源碼,發現它默認值返回的是false,也就說如果你不重載onInterceptTouchEvent方法並令其返回True,它一定是返回false,並能夠執行花括號內的代碼。

  我們分析一下花括號中的代碼,if (actionMasked == MotionEvent.ACTION_DOWN

                    || (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)

                    || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {}判斷當前的事件是否是ACTION_DOWN、ACTION_POINTER_DOWN(多點觸摸)、ACTION_HOVER_MOVE(懸停),如果是,執行花括號內代碼, 

final int childrenCount = mChildrenCount;

if (childrenCount != 0) {}判斷當前控件是否有子控件,如果大於0,執行花括號內代碼,

for (int i = childrenCount - 1; i >= 0; i–)遍歷子控件,

if (!canViewReceivePointerEvents(child)

  判斷當前的down、POINTER_DOWN、HOVER_MOVE三個事件的坐標點是否落在了子控件上,如果落在子控件上,

if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign))

  通過dispatchTransformedTouchEvent傳遞事件,交由子控件判斷是否傳遞或自己消費處理。如果dispatchTransformedTouchEvent返回true,表示子控件已消費處理,並添加此子控件View到觸摸鏈表,並放置鏈表頭,並結束遍歷子控件。newTouchTarget = addTouchTarget(child, idBitsToAssign);false表示未處理。

  接著分析
if (mFirstTouchTarget == null) {

                handled = dispatchTransformedTouchEvent(ev, canceled, null,

                        TouchTarget.ALL_POINTER_IDS);

   } else {

       ……

}

mFirstTouchTarget什麼時候為空呢?從前面的代碼可以看到,如果onInterceptTouchEvent返回為false(也就是不攔截),mFirstTouchTarget就為空,直接交給自己父View執行dispatchTouchEvent去了。如果mFirstTouchTarget不為空,它就取出觸摸鏈表,逐個遍歷判斷處理,如果前面比如Down事件處理過了,就不再處理了。

 

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