Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 事件傳遞(二):ViewGroup 的事件傳遞機制

編輯:關於 Android 程式設計

經過上一篇的實驗,我們只分析了 View 的事件傳遞,但還有個更厲害的角色——ViewGroup 一定要說一下。

從視圖層級來看,一邊是 View、一邊是 ViewGroup,而 ViewGroup 中又可以放入 View 和 ViewGroup。我們都知道 ViewGroup 可以擁有孩子,也能對孩子進行「拜訪」,而 View 沒有這些特性。那麼,它的事件傳遞機制與 View 究竟有何不同?下面分享筆者的實驗結果。

在 ViewGroup 中,事件傳遞多了一個方法:onInterceptTouchEvent(MotionEvent ev)。它的作用是讓 ViewGroup 攔截訊息。預設情況下,onInterceptTouchEvent 回傳 false,也就是不攔截;若回傳 true,事件就會被父控件攔截,不再向子 View 傳遞。

以下是我所做的測試代碼。

XML 佈局:

 <relativelayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">
    <com.chaoli_chen.ontouchdemo.myrelativelayout
        android:layout_height="match_parent" android:layout_width="match_parent"
        android:id="@+id/mrll">
        <com.chaoli_chen.ontouchdemo.mybutton
            android:id="@+id/bt" android:onclick="bt_click"
            android:layout_height="wrap_content" android:layout_width="wrap_content"
            android:text="實驗按鈕">
        </com.chaoli_chen.ontouchdemo.mybutton>
    </com.chaoli_chen.ontouchdemo.myrelativelayout>
</relativelayout>

自定義的 MyRelativeLayout,覆寫 dispatchTouchEvent、onInterceptTouchEvent、onTouchEvent 三個方法:

 public class MyRelativeLayout extends RelativeLayout {
    @Override public boolean dispatchTouchEvent(MotionEvent ev) {
        // 輸出 ACTION_DOWN / ACTION_UP
        return super.dispatchTouchEvent(ev);
    }
    @Override public boolean onInterceptTouchEvent(MotionEvent ev) {
        // 輸出 ACTION_DOWN / ACTION_UP
        return super.onInterceptTouchEvent(ev);
    }
    @Override public boolean onTouchEvent(MotionEvent event) {
        // 輸出 ACTION_DOWN / ACTION_UP
        return super.onTouchEvent(event);
    }
}

自定義的 MyButton 則覆寫 dispatchTouchEvent 與 onTouchEvent:

 public class Mybutton extends Button {
    @Override public boolean dispatchTouchEvent(MotionEvent event) {
        // 輸出 ACTION_DOWN / ACTION_UP
        return super.dispatchTouchEvent(event);
    }
    @Override public boolean onTouchEvent(MotionEvent event) {
        // 輸出 ACTION_DOWN / ACTION_UP
        return super.onTouchEvent(event);
    }
}

結果如下:

由結果分析可以看到:事件仍從 Activity 的 dispatchTouchEvent 進入,接著在自定義的 MyRelativeLayout 中先進行事件分發,然後執行是否攔截的判斷。查看 onInterceptTouchEvent 的預設 super 實現:

 public boolean onInterceptTouchEvent(MotionEvent ev) { return false; }

回傳 false,代表預設不攔截。最後事件傳遞到自定義的 Button 進行分發,再傳給 setOnTouchListener 方法,最終呼叫 onClick() 執行點擊事件。

有沒有發現,自定義的 MyRelativeLayout 並沒有觸發 setOnTouchListener?那是因為它把事件傳遞給了 Button,並未進行攔截。

接著看 onInterceptTouchEvent 回傳 true 的情況:

 @Override public boolean onInterceptTouchEvent(MotionEvent ev) {
    // 輸出 ACTION_DOWN / ACTION_UP
    return true;
}

測試結果:

是不是徹底明白了?當自定義的 MyRelativeLayout 進行事件攔截時,其內部的子 View 便不會響應事件,反而是 MyRelativeLayout 自己響應了 setOnTouchListener 與 setOnClickListener。至此,ViewGroup 事件傳遞的測試就完成了。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved