java – 在Android中检测左右摆动(onFling和OnGestureListener)
作者:互联网
我试图检测用户何时在活动中左转或右转.
目前我正在使用OnGestureListener和方法onFling(),我的问题是我没有找到一种很好的方法来检测它.
我想要一个类似于其他应用程序和“本机”Android摆动检测的行为但是使用代码(附后)我有很多错误的摇摆检测.如果有人已经解决了我想要的提示=)
这就是我正在使用的代码
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,float velocityY) {
//Get Position
float ev1X = e1.getX();
float ev2X = e2.getX();
//Get distance of X (e1) to X (e2)
final float xdistance = Math.abs(ev1X - ev2X);
//Get velocity of cursor
final float xvelocity = Math.abs(velocityX);
if( (xvelocity > SWIPE_MIN_VELOCITY) && (xdistance > SWIPE_MIN_DISTANCE) )
{
if(ev1X > ev2X)//Switch Left
{
if (Manager.debug) Log.d(Manager.appname,"SWING_LEFT_EVENT");
moveToRight();
}
else//Switch Right
{
if (Manager.debug) Log.d(Manager.appname,"SWING_RIGHT_EVENT");
moveToLeft();
}
}
return false;
}
解决方法:
我不确定它有多远,但我就是这样做的.
private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_MAX_OFF_PATH = 250;
private static final int SWIPE_THRESHOLD_VELOCITY = 100;
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
Log.d("---onFling---", e1.toString() + e2.toString() + "");
try {
if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
return false;
// right to left swipe
if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
//do your code
} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
//left to right flip
}
}
} catch (Exception e) {
// nothing
}
return false;
}
标签:multi-touch,android,java 来源: https://codeday.me/bug/20190726/1542145.html