基本步骤
- 触摸屏时,触发MotionEvent
- setOnTouchListener进行监听,获得MotionEvent
- GestureDetector将MotionEvent转发到OnGestureListener
- OnGestureListener中进行判断和响应
源码
public class MainActivity extends Activity {
ImageView image;
GestureDetector myDetector;
class myGesteureListener extends SimpleOnGestureListener{
@Override
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);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image = (ImageView) findViewById(R.id.imageView1);
myDetector = new GestureDetector(new myGesteureListener());
image.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
myDetector.onTouchEvent(event);
return true;
}
});
}
}
这种手势识别有很大的缺点,比如先左滑动,在不抬起手指情况下,又向右滑动,那么就不能很好的识别滑动动作。因此有必要改进识别方法。