我需要在代码中检测滑动方向。我可以检测到方向,但是如果我向右上方或左上方滑动就好了。同样的左边,我的要求是没有举起手指,如果我向左滑动它应该只剩下,同样所有的方向。谁能帮我吗。提前谢谢!
@覆盖 public boolean onTouchEvent(MotionEvent touchevent){
switch (touchevent.getAction()) {
// when the user first touches the screen we get x and y coordinate
case MotionEvent.ACTION_DOWN: {
x1 = touchevent.getX();
y1 = touchevent.getY();
break;
}
case MotionEvent.ACTION_MOVE: {
x2 = touchevent.getX();
y2 = touchevent.getY();
float deltaX = x2 - x1;
if (Math.abs(deltaX) > MIN_DISTANCE) {
// Left to Right swipe action
if (x2 > x1) {;
Log.e("RTL", "Right to Left Swap Performed");
}
else {
Log.e("LTR", "Left to Right Swap Performed");
}
} else {
if (y2 > y1) {
Log.e("UTD", "UP to Down Swap Performed");
}
// Right to left swipe action
else {
Log.e("DTU", "Down to UP Swap Performed");
}
}
}
}
return false;
}
答案 0 :(得分:0)
你应该计算角度,然后决定。如果矢量大于最小距离值,则可以检查角度。
float angle = (float) Math.toDegrees(Math.atan2(y2 - y1, x2 - x1));
if(angle > 45 && angle <= 135) return UP;
else if(angle > 135 && angle <= 225) return LEFT;
else if(angle > 225 && angle <= 315) return DOWN;
else return RIGHT;
答案 1 :(得分:0)
创建 GestureDetectorCompat 对象
GestureDetectorCompat gestureDetectorCompat;
并覆盖活动
中的 onTouchEvent @Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetectorCompat.onTouchEvent(event);
return true;
}
或者如果您想在某些视图中进行检测,则可以覆盖 onTouch
someView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
gestureDetectorCompat.onTouchEvent(motionEvent);
return false;
}
});
并初始化gestureDetectorCompat,如下所示,最好在 onCreate()中完成。
gestureDetectorCompat = new GestureDetectorCompat(this, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
float angle = (float) Math.toDegrees(Math.atan2(e1.getY() - e2.getY(), e2.getX() - e1.getX()));
if (angle > -45 && angle <= 45) {
Log.d(DEBUG_TAG, "Right to Left swipe performed");
return true;
}
if (angle >= 135 && angle < 180 || angle < -135 && angle > -180) {
Log.d(DEBUG_TAG, "Left to Right swipe performed");
return true;
}
if (angle < -45 && angle >= -135) {
Log.d(DEBUG_TAG, "Up to Down swipe performed");
return true;
}
if (angle > 45 && angle <= 135) {
Log.d(DEBUG_TAG, "Down to Up swipe performed");
return true;
}
return false;
}
});