GestureDetector一般我们会用ontouch来接收屏幕上的触摸事件,但是没办法接收滑动事件,我们可以通过这个GestureDetector来进行手势识别
首先呢要把ontouch的事件交给GestureDetector
// 手势来接管ontouch
@Override
public boolean onTouchEvent(MotionEvent event) {
mDetector.onTouchEvent(event);
return super.onTouchEvent(event);
}
然后进行具体操作了
mDetector = new GestureDetector(this, new SimpleOnGestureListener() {
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2,
float velocityX, float velocityY) {
//防止用户违法操作,Y轴大于200的时候不能操作
if(Math.abs(e2.getRawY()-e1.getRawY())>200){
return true;
}
// 左滑动,起点在那边向那边滑,然后用大数减去小
// 数判断是不是大于200个像素点
// 右滑动
if (e1.getRawX() - e2.getRawX() > 200) {
// TODO Auto-generated method stub
startActivity(new Intent(Setup1Activity.this,Setup2Activity.class));
finish();
//动画
package com.itheima.superman; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.View; import android.view.GestureDetector.SimpleOnGestureListener; public class Setup1Activity extends Activity { private GestureDetector mDetector; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_setup1); mDetector = new GestureDetector(this, new SimpleOnGestureListener() { @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { //防止用户违法操作,Y轴大于200的时候不能操作 if(Math.abs(e2.getRawY()-e1.getRawY())>200){ return true; } // 左滑动,起点在那边向那边滑,然后用大数减去小 // 数判断是不是大于200个像素点 // 右滑动 if (e1.getRawX() - e2.getRawX() > 200) { // TODO Auto-generated method stub startActivity(new Intent(Setup1Activity.this,Setup2Activity.class)); finish(); overridePendingTransition(R.anim.next_in, R.anim.next_out); return true; } return super.onFling(e1, e2, velocityX, velocityY); } }); } // 手势来接管ontouch @Override public boolean onTouchEvent(MotionEvent event) { mDetector.onTouchEvent(event); return super.onTouchEvent(event); } }
overridePendingTransition(R.anim.next_in, R.anim.next_out);
return true;
}
return super.onFling(e1, e2, velocityX, velocityY);
}
});