利用触摸屏的Fling、Scroll等Gesture(手势)操作来操作会使得应用程序的用户体验大大提升,比如用Scroll手势在 浏览器中滚屏,用Fling在阅读器中翻页等。在Android系统中,手势的识别是通过 GestureDetector.OnGestureListener接口来实现的,举例说明:
public class ActivityMain extends Activity implements GestureDetector.OnGestureListener {
GestureDetector detector;
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//构造GestureDetector;Context context, OnGestureListener listener
detector = new GestureDetector(this, this);
detector.setOnDoubleTapListener(new GestureDetector.OnDoubleTapListener() {
//短快的点击算一次单击
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
System.out.println("onSingleTapConfirmed");
return false;
}
//双击时产生一次
@Override
public boolean onDoubleTap(MotionEvent e) {
System.out.println("onDoubleTap");
return false;
}
//双击时产生两次
@Override
public boolean onDoubleTapEvent(MotionEvent e) {
System.out.println("onDoubleTapEvent");
return false;
}
});
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return detector.onTouchEvent(event);
}
// 用户轻触触摸屏,由1个MotionEvent ACTION_DOWN触发
@Override
public boolean onDown(MotionEvent e) {
System.out.println("onDown");
return false;
}
// 用户轻触触摸屏,尚未松开或拖动,由一个1个MotionEvent ACTION_DOWN触发
// 注意和onDown()的区别,强调的是没有松开或者拖动的状态
@Override
public void onShowPress(MotionEvent e) {
}
//用户(轻触触摸屏后)松开,由一个1个MotionEvent ACTION_UP触发
@Override
public boolean onSingleTapUp(MotionEvent e) {
System.out.println("onSingleTapUp");
return false;
}
// 用户按下触摸屏,并拖动,由1个MotionEvent ACTION_DOWN, 多个ACTION_MOVE触发
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
System.out.println("onScroll");
return false;
}
// 用户长按触摸屏,由多个MotionEvent ACTION_DOWN触发
@Override
public void onLongPress(MotionEvent e) {
System.out.println("onLongPress" + e.getEventTime());
}
//用户按下触摸屏、快速移动后松开,由1个MotionEvent ACTION_DOWN, 多个ACTION_MOVE, 1个ACTION_UP触发
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
System.out.println("onFling: " + (e1.getX() - e2.getX()) + " " + (e1.getY() - e2.getY()) + " " + velocityX + " " + velocityY);
System.out.println(e1.getY());
return false;
}
}