手勢識別的開發步驟:一:建立手勢庫
使用SDK內建例子GestureBuilder建立手勢庫(位置:android-sdk-windows\samples\android-8\GestureBuilder)。使用GestureBuilder之前,你需要恢複其到開發環境,然後進行編繹並部署到手機上。此時,就可以使用GestureBuilder建立手勢庫,產生的手勢庫檔案在SCDard上,預設檔案名稱為:gestures
二:在應用中載入手勢庫檔案,然後開發手勢識別代碼。
1、把手勢庫檔案gestures檔案拷貝到項目的res/raw目錄下。然後在布局檔案中添加用於手勢繪製的2、設定布局:
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
android:id="@+id/gestures"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gestureStrokeType="multiple"//設定為的多比劃,預設是一比劃。
android:layout_weight="10" />//設定組件的顯示優先順序,值越小優先順序越高。
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="recognize"
android:text="識別" />
3、業務代碼:
//手勢的activity類
public class DemoActivityextends Activity {
private GestureOverlayView gestures;
private Gesture myGesture;
private GestureLibrary library;
@Override
public void onCreate(BundlesavedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//擷取組件
gestures = (GestureOverlayView)this.findViewById(R.id.gestures);
載入手勢庫:目錄在res/raw/gestures
library = GestureLibraries.fromRawResource(this, R.raw.gestures);
//添加手勢組件的監聽
gestures.addOnGestureListener(newOnGestureListener() {
//手勢開始 的時候對應的回調
public void onGestureStarted(GestureOverlayView overlay,MotionEvent event) {
System.out.println("onGestureStarted");
}
//手勢結束的時候對應的回調(圖形畫好時的回呼函數)
public void onGestureEnded(GestureOverlayView overlay,MotionEvent event) {
// TODO Auto-generatedmethod stub
System.out.println("onGestureEnded");
//擷取在介面上所畫的Gesture
myGesture =overlay.getGesture();
}
//手勢取消的時候對應的回調
public void onGestureCancelled(GestureOverlayView overlay,MotionEvent event) {
}
//手指在螢幕上畫手勢的時候 對應的回調
public void onGesture(GestureOverlayView overlay, MotionEventevent) {
// TODO Auto-generatedmethod stub
System.out.println("onGesture");
}
});
}
//點擊按鈕的事件方法:
public void recognize(View view){
//載入手勢到手勢庫中。
library.load();
//識別剛才畫的手勢:按相似性放在集合中,集合中第一個元素是相似性最高的
ArrayListpredictions = library.recognize(myGesture);
//把匹配度最高的條目擷取出來
Predictionpredition = predictions.get(0);
//手勢的相似性大於等於5,就符合要求
if(predition.score>=5){
//predition.name:擷取手勢的名字
if("call".equals(predition.name)){
//撥打到電話
Intentintent = new Intent();
intent.setAction(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:13512345678"));
startActivity(intent);
}else if("close".equals(predition.name)){
//關閉當前的程式,即關閉當前的activity
finish();// 跟使用者在手機上點擊後退鍵的操作是一樣的
}else if("toast".equals(predition.name)){
Toast.makeText(this,"我是土司", 0).show();
}
}else{
Toast.makeText(this, "收拾不能被識別", 0).show();
}
//清除手勢
gestures.clear(true);
//取消手勢
//gestures.cancelGesture();
}
}
I18n 應用程式的國際化
在