2013年3月31日 星期日

[ Android Gesture ] GestureDetector手勢範例三

在Android手機中,有一套APP叫Gestures Builder,我們利用它來設計幾個手勢,如下圖:
接下來我們嘗試開發一套APP來讀取這個手勢,來控制畫面中,圓形圖案的顏色,當查覺到使用者輸入"2"時,則顯示紅色圓,否則為藍色圓。該APP執行結果如下圖:



其原始程式如下:
//MainActivity.java
package com.example.test;
import java.io.File;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.gesture.Gesture;
import android.gesture.GestureLibraries;
import android.gesture.GestureLibrary;
import android.gesture.GestureOverlayView;
import android.gesture.GestureOverlayView.OnGesturePerformedListener;
import android.gesture.Prediction;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends Activity implements OnGesturePerformedListener {
 private GestureLibrary gestureLib;
 DrawView drawView;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
   GestureOverlayView gestureOverlayView = new GestureOverlayView(this);
      View inflate = getLayoutInflater().inflate(R.layout.activity_main, null);
      gestureOverlayView.addView(inflate);
      drawView = new DrawView(this);
      gestureOverlayView.addView(drawView);
      gestureOverlayView.addOnGesturePerformedListener(this);
      gestureLib = GestureLibraries.fromFile(new File("/mnt/sdcard/gestures"));
      if (!gestureLib.load()) {
        finish();
      }
  setContentView(gestureOverlayView);
 }
 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.activity_main, menu);
  return true;
 }
 @Override
 public void onGesturePerformed(GestureOverlayView arg0, Gesture gesture) {
  // TODO Auto-generated method stub
    ArrayList<prediction> predictions = gestureLib.recognize(gesture);
      for (Prediction prediction : predictions) {
        if (prediction.score > 1.0) {
          Toast.makeText(this, prediction.name+"  "+Double.toString(prediction.score),
  Toast.LENGTH_SHORT).show();
          if(prediction.name.contains("2"))
             drawView.setState(1);
          else
           drawView.setState(0);
         break;
        }
      }   
 }
}

//DrawView.java
package com.example.test;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;
public class DrawView extends View {
 Paint paint;
 int state = 0;
 public DrawView(Context context) {
  super(context);
  paint=new Paint();  // TODO Auto-generated constructor stub
 }
 @Override
 protected void onDraw(Canvas canvas) {
  // TODO Auto-generated method stub
  switch(state){
  case 0:
   paint.setColor(Color.BLUE);
   break;
  case 1:
   paint.setColor(Color.RED);
   break;
  }

  canvas.drawCircle(10, 10, 10, paint);
  super.onDraw(canvas);
 }
 public void setState(int s){
  state = s;
  invalidate();
 }
}

沒有留言:

張貼留言