屏幕滑动的方法,亲测可用(直接复制即可)
方法一:
float x1 = 0;
float x2 = 0;
float y1 = 0;
float y2 = 0;
@Override
public boolean onTouchEvent(MotionEvent event) {
//继承了Activity的onTouchEvent方法,直接监听点击事件
if(event.getAction() == MotionEvent.ACTION_DOWN) {
//当手指按下的时候
x1 = event.getX();
y1 = event.getY();
}
if(event.getAction() == MotionEvent.ACTION_UP) {
//当手指离开的时候
x2 = event.getX();
y2 = event.getY();
if(y1 - y2 > 50) {
Toast.makeText(getApplicationContext(), "向上滑", Toast.LENGTH_SHORT).show();
} else if(y2 - y1 > 50) {
Toast.makeText(getApplicationContext(), "向下滑", Toast.LENGTH_SHORT).show();
} else if(x1 - x2 > 50) {
Toast.makeText(getApplicationContext(), "向左滑", Toast.LENGTH_SHORT).show();
} else if(x2 - x1 > 50) {
Toast.makeText(getApplicationContext(), "向右滑", Toast.LENGTH_SHORT).show();
}
}
return super.onTouchEvent(event);
}
方法二:在Activity中
- 定义变量
//定义滑动的最小距离
private static final int MIN_DISTANCE=100;
private GestureDetector gestureDetector;
private MyGestureDetector myGestureDetector;
- 实例化
//实例化MyGestureDetector
myGestureDetector=new MyGestureDetector();
//实例化GestureDetector并将MyGestureDetector实例传入
gestureDetector=new GestureDetector(this,myGestureDetector);
- 重写onTouchEvent返回一个gestureDetector的屏幕触摸事件
/**//**
* 重写onTouchEvent返回一个gestureDetector的屏幕触摸事件
*//**/
@Override
public boolean onTouchEvent(MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
class MyGestureDetector extends GestureDetector.SimpleOnGestureListener{
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
if(e1.getX()-e2.getX()>MIN_DISTANCE){
Toast.makeText(MainActivity.this,"左滑",Toast.LENGTH_SHORT).show();
}else if(e2.getX()-e1.getX()>MIN_DISTANCE){
Toast.makeText(MainActivity.this,"右滑",Toast.LENGTH_SHORT).show();
}else if(e1.getY()-e2.getY()>MIN_DISTANCE){
Toast.makeText(MainActivity.this,"上滑",Toast.LENGTH_SHORT).show();
}else if(e2.getY()-e1.getY()>MIN_DISTANCE){
Toast.makeText(MainActivity.this,"下滑",Toast.LENGTH_SHORT).show();
}
return true;
}
}