开发者

Android recognizing gestures

I imported the gesture example and created my own app. There is a button and the gestureoverlayview in the layout. The button starts the GestureBuilderActivity.class, where I can add or remove gestures (this is the example). Under the button, in the GestureOverlayView I can draw gestures. Layout:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
  <Button  
    android:layout_width=开发者_如何学JAVA"fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Click to see gestures"
    android:id="@+id/Button01"
    />
    <android.gesture.GestureOverlayView
    android:id="@+id/gestures"
    android:layout_width="fill_parent" 
    android:layout_height="0dip"
    android:layout_weight="1.0" />
</LinearLayout>

From the example I know that this is where I find the gestures:

 final String path = new File(Environment.getExternalStorageDirectory(),
                    "gestures").getAbsolutePath();

and the toast msg shows (still in the example) that the gesture is saved in /mnt/sdcard/gestures:

Toast.makeText(this, getString(R.string.save_success, path), Toast.LENGTH_LONG).show();

How can I make the app recognize the gesture I draw and show me its name in a toast msg?


First, I would read this short article that explains how to use gestures.

To recognize a gesture you need to provide an OnGesturePerformedListener to GestureOverlayView. In this example, I just had the Activity implement the OnGesturePerformedListener.

public class MyActivity extends Activity implements OnGesturePerformedListener {

private GestureLibrary mGestures;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // I use resources but you may want to use GestureLibraries.fromFile(path)
    mGestures = GestureLibraries.fromRawResource(this, R.raw.gestures);
    if (!mGestures.load()) {
        showDialog(DIALOG_LOAD_FAIL);
        finish();
    }

    // register the OnGesturePerformedListener (i.e. this activity)
    GestureOverlayView gesturesView = (GestureOverlayView) findViewById(R.id.gestures);
    gesturesView.addOnGesturePerformedListener(this);
}

public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) {
    ArrayList<Prediction> predictions = mGestures.recognize(gesture);

        // Determine if a gesture was performed.  
        // This can be tricky, here is a simple approach.
    Prediction prediction = (predictions.size() != 0) ? predictions.get(0) : null;
    prediction = (prediction.score >= 1.0) ? prediction: null;

    if (prediction != null) {
           // do something with the prediction
           Toast.makeText(this, prediction.name + "(" + prediction.score + ")", Toast.LENGTH_LONG).show();
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜