步骤
- 自定义手势文件(使用安卓模拟器中自带的软件Gestures builder绘制并命名。然后在模拟器SD卡根目录中找到名为gesture的文件,复制到项目的res/raw文件夹下)
- 布局文件中添加GestureOverlayView组件,该组件可以包含其他组件,也可覆盖其他组件
- GestureLibrary 找到并加载手势文件
- GestureOverlayView对手势进行识别和匹配,这里使用onGesturePerformed(执行中手势)
源码
1、activity_main布局文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
tools:context=".MainActivity">
<android.gesture.GestureOverlayView
android:id="@+id/gestureOverlayView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/pic1" />
</android.gesture.GestureOverlayView>
</LinearLayout>
2、MainActivity
public class MainActivity extends Activity {
GestureOverlayView myGestureOverlayView;
GestureLibrary myGestureLibrary;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myGestureOverlayView = (GestureOverlayView) findViewById(R.id.gestureOverlayView1);
// 找到手势文件并加载
myGestureLibrary = GestureLibraries.fromRawResource(this,
R.raw.gestures);
myGestureLibrary.load();
myGestureOverlayView
.addOnGesturePerformedListener(new OnGesturePerformedListener() {
@Override
public void onGesturePerformed(GestureOverlayView overlay,
Gesture gesture) {
ArrayList<Prediction> myGesture = myGestureLibrary
.recognize(gesture);
Prediction prediction = myGesture.get(0);
// 只要相似度大于5.0就符合
if (prediction.score > 5.0) {
// 通过手势名判断是哪种手势
if (prediction.name.equals("exit")) {
finish();
} else if (prediction.name.equals("left")) {
Toast.makeText(MainActivity.this, "往左滑动!",
Toast.LENGTH_SHORT).show();
} else if (prediction.name.equals("right")) {
Toast.makeText(MainActivity.this, "往右滑动!",
Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(MainActivity.this, "没有相似手势",
Toast.LENGTH_SHORT).show();
}
}
});
}
}