手势

  • 使用GestureDetector进行手势识别
手势交互原理

eg:当滑动图片时弹出从那边滑动
1.设置图片
在ImageView中加载图片为
android:src="@drawable/tupian"
2.获得图像id并设置监听

ImageView image=(ImageView)findViewById(R.id.imageView);
image.setOnTouchListener(new OnTouchListener{
GestureDetector myGesture=new GestureDetector(new myGesture);
  public boolean OnTouch(View view,MotionEvent event){
         myGestureDetector.onTouchEvent(event);
         return true;//设置成true表示触摸事件发生
}  

}
)

3.获得OnGestureListener类以便被实例化,在其中设置滑动方式

class myGesture extends OnGestureListener{
   public boolean onFling(MotionEvent e1,MotionEvent e2,float velocityX,float velocityY){
      if(e1.getX()-e2.getX()>50){
            Toast.makeText(MainActivity.this, "从右向左滑动", Toast.LENGTH_SHORT).show();
}else if(e2.getX()-e1.getX()>50){
            Toast.makeText(MainActivity.this, "从左向右滑动", Toast.LENGTH_SHORT).show();
}
  return super.onFling(e1,e2,velocityX,velocityY);
}
}
  • 使用GestureOverlayView进行手势识别
    1.导出手势:
    在Gesture Builder中建立手势在File Explore中导出file explore-shell-emulate-0-gesture进行导出
gesture手势

2.把手势gesture加入res-raw中

手势存储位置

3.找到刚才的手势文件并加载

GestureOverlayView gesture=(GestureOverlayView)findViewById(R.id.gestureOverlayView);
final GestureLibrary library=GestureLibraries.findRawResource(MainActivity.this,R.raw.gestures);

library.load();
4.匹配相应手势

//OnGesturePerformedListener手势执行监听器
gesture.addOnGesturePerformedListener(new OnGesturePerformedListener(){
   public void onGesturePerformed(GestureOverlayView gestureOver,Gesture gesture){
       ArrayList<Prediction> myGesture=library.recognize(gesture);
//Prediction表示手势的相似度
        Prediction prediction=myGesture.get(0);
        if(prediction.score>5){
             if(prediction.name.equals("next")){
     Toast.makeText(MainActivity.this,"播放下一首",Toast.LENGTH_SHORT);
}if(prediction.name.equals("previous")){
     Toast.makeText(MainActivity.this,"播放上一首",Toast.LENGTH_SHORT);
}if(prediction.name.equals("quit")){
     Toast.makeText(MainActivity.this,"退出",Toast.LENGTH_SHORT);
}

}else{
     Toast.makeText(MainActivity.this,"没有相关手势",Toast.LENGTH_SHORT);
}
}
});

4.设置手势的类型
在android.gesture.GestureOverlayView标签中设置
设置笔画颜色android:gestureColor="#ff0000"
设置笔画类型android:gestureStrokeType="multiple"
设置笔画宽度android:gestureStrokeWidth="2"
用户画完手势效果淡出时间android:fadeDuration
当手势被识别后,是否拦截该手势android:eventsInterceptionEnable
手势是否自动淡出android:fadeEnable

推荐阅读更多精彩内容