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

Android VelocityTracker 詳解:追蹤手勢滑動速度

編輯:關於 Android 程式設計

android.view.VelocityTracker 主要用於追蹤觸控螢幕事件(如 flinging 快速滑動及其他手勢)的速度。本文將介紹它的核心用法與常用方法。

基本運作原理

使用 VelocityTracker 時,先透過 addMovement(MotionEvent) 把觸控事件加入物件中;接著在需要時呼叫 computeCurrentVelocity(int) 計算速度,最後再以 getXVelocity() 或 getYVelocity() 取得水平與垂直方向的速度。

需要特別注意的是:在呼叫 get 系列方法取得速度之前,必須先呼叫 computeCurrentVelocity(int) 完成速度單位的初始化,否則取得到的值可能不正確。

主要方法一覽

  • void addMovement(MotionEvent event):將使用者的移動事件加入追蹤器。
  • void clear():將追蹤器重設回初始狀態。
  • void computeCurrentVelocity(int units, float maxVelocity):依已收集的點計算目前速度。參數 units 代表速度的時間單位——值為 1 表示「每毫秒移動的像素數」,值為 1000 則表示「每秒移動的像素數」;maxVelocity 為速度上限。
  • void computeCurrentVelocity(int units):等同以 Float.MAX_VALUE 作為最大速度呼叫上面的方法。
  • float getXVelocity() / float getYVelocity():取得最後一次計算的水平/垂直速度。
  • float getXVelocity(int id) / float getYVelocity(int id):針對特定手指(多點觸控)取得速度。
  • static VelocityTracker obtain():取得一個 VelocityTracker 實例。
  • void recycle():將物件歸還資源池以供重複使用。

使用範例

private VelocityTracker mVelocityTracker;  // 宣告變數

// 在 onTouchEvent(MotionEvent ev) 中:
if (mVelocityTracker == null) {
    mVelocityTracker = VelocityTracker.obtain();  // 取得實例
}
mVelocityTracker.addMovement(ev);                 // 加入移動事件

// 當事件為 MotionEvent.ACTION_UP 時計算速度
final VelocityTracker velocityTracker = mVelocityTracker;

// units 設為 1(每毫秒像素數),maxVelocity 設為 0.01
// 當實際速度大於 0.01 時顯示 0.01,小於 0.01 時顯示正常值
velocityTracker.computeCurrentVelocity(1, (float) 0.01);
Log.i("test", "velocityTraker" + velocityTracker.getXVelocity());

// units 設為 1000,代表每秒移動的像素數
velocityTracker.computeCurrentVelocity(1000);
Log.i("test", "velocityTraker" + velocityTracker.getXVelocity());

使用流程總結

  1. 需要追蹤觸控速度時,以 obtain() 取得 VelocityTracker 實例。
  2. 在 onTouchEvent 回呼中,以 addMovement(MotionEvent) 傳入目前的移動事件。
  3. 以 computeCurrentVelocity(int units) 計算速度。
  4. 以 getXVelocity()、getYVelocity() 取得目前速度。

透過 VelocityTracker,你就能為自訂 UI 加入順滑的甩動(fling)效果,例如判斷使用者快速滑動後觸發相應的滾動或翻頁動畫。

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