> 編寫:[Andrwyw](https://github.com/Andrwyw) - 原文:[http://developer.android.com/training/gestures/viewgroup.html](http://developer.android.com/training/gestures/viewgroup.html)
因為很多時候event的目標是ViewGroup的孩子,并不是ViewGroup本身,所以處理[ViewGroup](http://developer.android.com/reference/android/view/ViewGroup.html)中的觸摸事件需要特別注意。為了確保每個view能正確地接受到它們想要的觸摸事件,可以重載[onInterceptTouchEvent()](http://developer.android.com/reference/android/view/ViewGroup.html#onInterceptTouchEvent(android.view.MotionEvent))函數。
### 在ViewGroup中截獲觸摸事件
每當在[ViewGroup](http://developer.android.com/reference/android/view/ViewGroup.html)的表面上檢測到一個觸摸事件,包括它子view的表面,`onInterceptTouchEvent()`都會被調用。如果`onInterceptTouchEvent()`返回`true`,[MotionEvent](http://developer.android.com/reference/android/view/MotionEvent.html)就被截獲了,這表示它不會被傳遞給孩子了,而是傳遞給該父view自身的[onTouchEvent()](http://developer.android.com/reference/android/view/View.html#onTouchEvent(android.view.MotionEvent))方法。
`onInterceptTouchEvent()`方法讓父view能夠在它的子view之前處理觸摸事件。如果你讓`onInterceptTouchEvent()`返回`true`,則之前處理觸摸事件的子view會收到[ACTION_CANCEL](http://developer.android.com/reference/android/view/MotionEvent.html#ACTION_CANCEL)事件,并且該點之后的事件會被發送給該父view自身的`onTouchEvent()`函數,進行常規處理。`onInterceptTouchEvent()`也可以返回`false`,這樣事件沿view層級分發到目標前,父view可以簡單地觀察該事件。這里的目標是指,通過`onTouchEvent()`處理消息事件的view。
接下來的代碼段中,`MyViewGroup`繼承自[ViewGroup](http://developer.android.com/reference/android/view/ViewGroup.html)。`MyViewGroup`有多個子view。如果你水平地拖動手指經過某個子view,該子view不會接收到觸摸事件,而是`MyViewGroup`處理這些觸摸事件來滾動它的內容。然而,如果你點擊子view中的button,或垂直地滾動子view,則父view不會截獲這些觸摸事件,因為子view本就是預定目標。在這些情況下,`onInterceptTouchEvent()`應該返回`false`,`MyViewGroup`的`onTouchEvent()`也不會被調用。
~~~
public class MyViewGroup extends ViewGroup {
private int mTouchSlop;
...
ViewConfiguration vc = ViewConfiguration.get(view.getContext());
mTouchSlop = vc.getScaledTouchSlop();
...
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
/*
* This method JUST determines whether we want to intercept the motion.
* If we return true, onTouchEvent will be called and we do the actual
* scrolling there.
*/
final int action = MotionEventCompat.getActionMasked(ev);
// Always handle the case of the touch gesture being complete.
if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) {
// Release the scroll.
mIsScrolling = false;
return false; // Do not intercept touch event, let the child handle it
}
switch (action) {
case MotionEvent.ACTION_MOVE: {
if (mIsScrolling) {
// We're currently scrolling, so yes, intercept the
// touch event!
return true;
}
// If the user has dragged her finger horizontally more than
// the touch slop, start the scroll
// left as an exercise for the reader
final int xDiff = calculateDistanceX(ev);
// Touch slop should be calculated using ViewConfiguration
// constants.
if (xDiff > mTouchSlop) {
// Start scrolling!
mIsScrolling = true;
return true;
}
break;
}
...
}
// In general, we don't want to intercept touch events. They should be
// handled by the child view.
return false;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
// Here we actually handle the touch event (e.g. if the action is ACTION_MOVE,
// scroll this container).
// This method will only be called if the touch event was intercepted in
// onInterceptTouchEvent
...
}
}
~~~
注意[ViewGroup](http://developer.android.com/reference/android/view/ViewGroup.html)也提供了[requestDisallowInterceptTouchEvent()](http://developer.android.com/reference/android/view/ViewGroup.html#requestDisallowInterceptTouchEvent(boolean))方法。當子view不想該父view和祖先view通過`onInterceptTouchEvent()`截獲它的觸摸事件時,可調用[ViewGroup](http://developer.android.com/reference/android/view/ViewGroup.html)的該方法。
### 使用ViewConfiguration的常量
上面的代碼段中使用了當前的[ViewConfiguration](http://developer.android.com/reference/android/view/ViewConfiguration.html)來初始化`mTouchSlop`變量。你可以使用[ViewConfiguration](http://developer.android.com/reference/android/view/ViewConfiguration.html)類來獲取Android系統常用的一些距離、速度、時間值。
“Touch slop”是指在被識別為移動的手勢前,用戶觸摸可移動的那一段像素距離。Touch slop通常用來預防用戶在做一些其他觸摸操作時,出現意外地滑動,例如觸摸屏幕上的元素。
另外兩個常用的[ViewConfiguration](http://developer.android.com/reference/android/view/ViewConfiguration.html)函數是[getScaledMinimumFlingVelocity()](http://developer.android.com/reference/android/view/ViewConfiguration.html#getScaledMinimumFlingVelocity())和[getScaledMaximumFlingVelocity()](http://developer.android.com/reference/android/view/ViewConfiguration.html#getScaledMaximumFlingVelocity())。這兩個函數會返回初始化一個快速滑動(fling)的最小、最大速度(分別地),以像素每秒為測量單位。如:
~~~
ViewConfiguration vc = ViewConfiguration.get(view.getContext());
private int mSlop = vc.getScaledTouchSlop();
private int mMinFlingVelocity = vc.getScaledMinimumFlingVelocity();
private int mMaxFlingVelocity = vc.getScaledMaximumFlingVelocity();
...
case MotionEvent.ACTION_MOVE: {
...
float deltaX = motionEvent.getRawX() - mDownX;
if (Math.abs(deltaX) > mSlop) {
// A swipe occurred, do something
}
...
case MotionEvent.ACTION_UP: {
...
} if (mMinFlingVelocity
~~~
### 擴展view的可觸摸區域
Android提供了[TouchDelegate](http://developer.android.com/reference/android/view/TouchDelegate.html)類,讓父view擴展子view的可觸摸區域,擴展后的區域可超過子view本身的邊界。這在子view很小,但需要一個更大的觸摸區域時非常有用。如果需要,你也可以使用這種方式來實現對子view的觸摸區域的收縮。
在下面的例子中,[ImageButton](http://developer.android.com/reference/android/widget/ImageButton.html)對象是所謂的"delegate view"(是指觸摸區域將被父view擴展的那個子view)。這是布局文件:
~~~
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/parent_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<ImageButton android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@null"
android:src="@drawable/icon" />
</RelativeLayout>
~~~
下面的代碼段做了這樣幾件事:
- 獲得父view對象并發送一段[Runnable](http://developer.android.com/reference/java/lang/Runnable.html)到UI線程。這會確保父view在調用[getHitRect()](http://developer.android.com/reference/android/view/View.html#getHitRect(android.graphics.Rect))函數前會布局它的子view。`getHitRect()`函數會獲得子view在父view坐標系中的點擊矩形(觸摸區域)。
- 找到[ImageButton](http://developer.android.com/reference/android/widget/ImageButton.html)子view,然后調用`getHitRect()`來獲得它的觸摸區域的邊界。
- 擴展[ImageButton](http://developer.android.com/reference/android/widget/ImageButton.html)的點擊矩形的邊界。
- 實例化一個[TouchDelegate](http://developer.android.com/reference/android/view/TouchDelegate.html)對象,并把擴展過的點擊矩形和[ImageButton](http://developer.android.com/reference/android/widget/ImageButton.html)子view作為參數傳遞給它。
- 設置父view的[TouchDelegate](http://developer.android.com/reference/android/view/TouchDelegate.html),這樣在touch delegate邊界內的點擊就會傳遞到該子view上。
在[ImageButton](http://developer.android.com/reference/android/widget/ImageButton.html)子view的touch delegate范圍內,父view會接收到所有的觸摸事件。如果觸摸事件發生在子view自身的點擊矩形中,父view會把觸摸事件交給子view處理。
~~~
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get the parent view
View parentView = findViewById(R.id.parent_layout);
parentView.post(new Runnable() {
// Post in the parent's message queue to make sure the parent
// lays out its children before you call getHitRect()
@Override
public void run() {
// The bounds for the delegate view (an ImageButton
// in this example)
Rect delegateArea = new Rect();
ImageButton myButton = (ImageButton) findViewById(R.id.button);
myButton.setEnabled(true);
myButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this,
"Touch occurred within ImageButton touch region.",
Toast.LENGTH_SHORT).show();
}
});
// The hit rectangle for the ImageButton
myButton.getHitRect(delegateArea);
// Extend the touch area of the ImageButton beyond its bounds
// on the right and bottom.
delegateArea.right += 100;
delegateArea.bottom += 100;
// Instantiate a TouchDelegate.
// "delegateArea" is the bounds in local coordinates of
// the containing view to be mapped to the delegate view.
// "myButton" is the child view that should receive motion
// events.
TouchDelegate touchDelegate = new TouchDelegate(delegateArea,
myButton);
// Sets the TouchDelegate on the parent view, such that touches
// within the touch delegate bounds are routed to the child.
if (View.class.isInstance(myButton.getParent())) {
((View) myButton.getParent()).setTouchDelegate(touchDelegate);
}
}
});
}
}
~~~
- 序言
- Android入門基礎:從這里開始
- 建立第一個App
- 創建Android項目
- 執行Android程序
- 建立簡單的用戶界面
- 啟動其他的Activity
- 添加ActionBar
- 建立ActionBar
- 添加Action按鈕
- 自定義ActionBar的風格
- ActionBar的覆蓋層疊
- 兼容不同的設備
- 適配不同的語言
- 適配不同的屏幕
- 適配不同的系統版本
- 管理Activity的生命周期
- 啟動與銷毀Activity
- 暫停與恢復Activity
- 停止與重啟Activity
- 重新創建Activity
- 使用Fragment建立動態的UI
- 創建一個Fragment
- 建立靈活動態的UI
- Fragments之間的交互
- 數據保存
- 保存到Preference
- 保存到文件
- 保存到數據庫
- 與其他應用的交互
- Intent的發送
- 接收Activity返回的結果
- Intent過濾
- Android分享操作
- 分享簡單的數據
- 給其他App發送簡單的數據
- 接收從其他App返回的數據
- 給ActionBar增加分享功能
- 分享文件
- 建立文件分享
- 分享文件
- 請求分享一個文件
- 獲取文件信息
- 使用NFC分享文件
- 發送文件給其他設備
- 接收其他設備的文件
- Android多媒體
- 管理音頻播放
- 控制音量與音頻播放
- 管理音頻焦點
- 兼容音頻輸出設備
- 拍照
- 簡單的拍照
- 簡單的錄像
- 控制相機硬件
- 打印
- 打印照片
- 打印HTML文檔
- 打印自定義文檔
- Android圖像與動畫
- 高效顯示Bitmap
- 高效加載大圖
- 非UI線程處理Bitmap
- 緩存Bitmap
- 管理Bitmap的內存
- 在UI上顯示Bitmap
- 使用OpenGL ES顯示圖像
- 建立OpenGL ES的環境
- 定義Shapes
- 繪制Shapes
- 運用投影與相機視圖
- 添加移動
- 響應觸摸事件
- 添加動畫
- View間漸變
- 使用ViewPager實現屏幕側滑
- 展示卡片翻轉動畫
- 縮放View
- 布局變更動畫
- Android網絡連接與云服務
- 無線連接設備
- 使得網絡服務可發現
- 使用WiFi建立P2P連接
- 使用WiFi P2P服務
- 執行網絡操作
- 連接到網絡
- 管理網絡
- 解析XML數據
- 高效下載
- 為網絡訪問更加高效而優化下載
- 最小化更新操作的影響
- 避免下載多余的數據
- 根據網絡類型改變下載模式
- 云同步
- 使用備份API
- 使用Google Cloud Messaging
- 解決云同步的保存沖突
- 使用Sync Adapter傳輸數據
- 創建Stub授權器
- 創建Stub Content Provider
- 創建Sync Adpater
- 執行Sync Adpater
- 使用Volley執行網絡數據傳輸
- 發送簡單的網絡請求
- 建立請求隊列
- 創建標準的網絡請求
- 實現自定義的網絡請求
- Android聯系人與位置信息
- Android聯系人信息
- 獲取聯系人列表
- 獲取聯系人詳情
- 使用Intents修改聯系人信息
- 顯示聯系人頭像
- Android位置信息
- 獲取最后可知位置
- 獲取位置更新
- 顯示位置地址
- 創建和監視地理圍欄
- Android可穿戴應用
- 賦予Notification可穿戴特性
- 創建Notification
- 在Notifcation中接收語音輸入
- 為Notification添加顯示頁面
- 以Stack的方式顯示Notifications
- 創建可穿戴的應用
- 創建并運行可穿戴應用
- 創建自定義的布局
- 添加語音功能
- 打包可穿戴應用
- 通過藍牙進行調試
- 創建自定義的UI
- 定義Layouts
- 創建Cards
- 創建Lists
- 創建2D-Picker
- 創建確認界面
- 退出全屏的Activity
- 發送并同步數據
- 訪問可穿戴數據層
- 同步數據單元
- 傳輸資源
- 發送與接收消息
- 處理數據層的事件
- Android TV應用
- 創建TV應用
- 創建TV應用的第一步
- 處理TV硬件部分
- 創建TV的布局文件
- 創建TV的導航欄
- 創建TV播放應用
- 創建目錄瀏覽器
- 提供一個Card視圖
- 創建詳情頁
- 顯示正在播放卡片
- 幫助用戶在TV上探索內容
- TV上的推薦內容
- 使得TV App能夠被搜索
- 使用TV應用進行搜索
- 創建TV游戲應用
- 創建TV直播應用
- TV Apps Checklist
- Android企業級應用
- Ensuring Compatibility with Managed Profiles
- Implementing App Restrictions
- Building a Work Policy Controller
- Android交互設計
- 設計高效的導航
- 規劃屏幕界面與他們之間的關系
- 為多種大小的屏幕進行規劃
- 提供向下和橫向導航
- 提供向上和歷史導航
- 綜合:設計樣例 App
- 實現高效的導航
- 使用Tabs創建Swipe視圖
- 創建抽屜導航
- 提供向上的導航
- 提供向后的導航
- 實現向下的導航
- 通知提示用戶
- 建立Notification
- 當啟動Activity時保留導航
- 更新Notification
- 使用BigView風格
- 顯示Notification進度
- 增加搜索功能
- 建立搜索界面
- 保存并搜索數據
- 保持向下兼容
- 使得你的App內容可被Google搜索
- 為App內容開啟深度鏈接
- 為索引指定App內容
- Android界面設計
- 為多屏幕設計
- 兼容不同的屏幕大小
- 兼容不同的屏幕密度
- 實現可適應的UI
- 創建自定義View
- 創建自定義的View類
- 實現自定義View的繪制
- 使得View可交互
- 優化自定義View
- 創建向后兼容的UI
- 抽象新的APIs
- 代理至新的APIs
- 使用舊的APIs實現新API的效果
- 使用版本敏感的組件
- 實現輔助功能
- 開發輔助程序
- 開發輔助服務
- 管理系統UI
- 淡化系統Bar
- 隱藏系統Bar
- 隱藏導航Bar
- 全屏沉浸式應用
- 響應UI可見性的變化
- 創建使用Material Design的應用
- 開始使用Material Design
- 使用Material的主題
- 創建Lists與Cards
- 定義Shadows與Clipping視圖
- 使用Drawables
- 自定義動畫
- 維護兼容性
- Android用戶輸入
- 使用觸摸手勢
- 檢測常用的手勢
- 跟蹤手勢移動
- Scroll手勢動畫
- 處理多觸摸手勢
- 拖拽與縮放
- 管理ViewGroup中的觸摸事件
- 處理鍵盤輸入
- 指定輸入法類型
- 處理輸入法可見性
- 兼容鍵盤導航
- 處理按鍵動作
- 兼容游戲控制器
- 處理控制器輸入動作
- 支持不同的Android系統版本
- 支持多個控制器
- Android后臺任務
- 在IntentService中執行后臺任務
- 創建IntentService
- 發送工作任務到IntentService
- 報告后臺任務執行狀態
- 使用CursorLoader在后臺加載數據
- 使用CursorLoader執行查詢任務
- 處理查詢的結果
- 管理設備的喚醒狀態
- 保持設備的喚醒
- 制定重復定時的任務
- Android性能優化
- 管理應用的內存
- 代碼性能優化建議
- 提升Layout的性能
- 優化layout的層級
- 使用include標簽重用layouts
- 按需加載視圖
- 使得ListView滑動順暢
- 優化電池壽命
- 監測電量與充電狀態
- 判斷與監測Docking狀態
- 判斷與監測網絡連接狀態
- 根據需要操作Broadcast接受者
- 多線程操作
- 在一個線程中執行一段特定的代碼
- 為多線程創建線程池
- 啟動與停止線程池中的線程
- 與UI線程通信
- 避免出現程序無響應ANR
- JNI使用指南
- 優化多核處理器(SMP)下的Android程序
- Android安全與隱私
- Security Tips
- 使用HTTPS與SSL
- 為防止SSL漏洞而更新Security
- 使用設備管理條例增強安全性
- Android測試程序
- 測試你的Activity
- 建立測試環境
- 創建與執行測試用例
- 測試UI組件
- 創建單元測試
- 創建功能測試
- 術語表