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

Android Gesture 手勢識別用法詳解

編輯:關於 Android 程式設計

本文透過實例分析 Android 中 Gesture 手勢識別的用法,分享給大家參考,具體如下:

很高興能在 Android 1.6 的 SDK 中看到手勢識別這個功能。在此之前我一直思考:要如何在 Android 上實現類似 NDS 遊戲那樣用手勢(更精確地說是筆勢)來操控遊戲角色?如今总算看到一絲曙光。不過,若要讓手勢像筆勢一樣隨心所欲地控制人物,仍有不少細節需要處理。

在 Android 1.6 的模擬器中預裝了一個名為 Gestures Builder 的程式,它就是用來讓你建立自訂手勢的(Gestures Builder 的源碼在 SDK 的 samples 目錄裡,有興趣可以研究)。建立好的手勢會被存到 /sdcard/gestures,把這個檔案複製到工程的 res/raw 下,就能在專案中使用這些手勢。複製到 res/raw 下的手勢是唯讀的,也就是說你無法再修改或新增手勢;若想實現增改,可以直接載入 SD 卡中的 gestures 檔案。

在範例中,我建立了這樣的手勢:

第二步:在 layout 中建立 GestureOverlayView,這個透明的 view 就是供你在上面畫手勢用的,可以疊在其他 View 之上:

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <android.gesture.GestureOverlayView android:id="@+id/gestures" android:layout_width="fill_parent" android:layout_height="0dip" android:layout_weight="1.0" /> </LinearLayout> 

第三步:載入 Gesture:

 mLibrary = GestureLibraries.fromRawResource(this, R.raw.gestures); if (!mLibrary.load()) { finish(); }

第四步:加上 OnGesturePerformedListener 的響應函式:

 GestureOverlayView gestures = (GestureOverlayView) findViewById(R.id.gestures); gestures.addOnGesturePerformedListener(this);

完成以上四步,就能打造出一個簡單的 Gesture 識別原型了。

程式運行結果如下:書寫一個 a 字,程式識別後便 toast 出一個 a:

完整程式碼如下:

 package com.ray.test; import java.util.ArrayList; import android.app.Activity; import android.gesture.Gesture; import android.gesture.GestureLibraries; import android.gesture.GestureLibrary; import android.gesture.GestureOverlayView; import android.gesture.Prediction; import android.gesture.GestureOverlayView.OnGesturePerformedListener; import android.os.Bundle; import android.widget.Toast; public class TestGesture extends Activity implements OnGesturePerformedListener{ GestureLibrary mLibrary; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); GestureOverlayView gestures = (GestureOverlayView) findViewById(R.id.gestures); gestures.addOnGesturePerformedListener(this); mLibrary = GestureLibraries.fromRawResource(this, R.raw.gestures); if (!mLibrary.load()) { finish(); } } @Override public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) { ArrayList predictions = mLibrary.recognize(gesture); // We want at least one prediction if (predictions.size() > 0) { Prediction prediction = (Prediction) predictions.get(0); // We want at least some confidence in the result if (prediction.score > 1.0) { // Show the spell Toast.makeText(this, prediction.name, Toast.LENGTH_SHORT).show(); } } } } 

希望本文所述能對大家的 Android 程式設計有所幫助。

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