Swipe left, right, up and down depending on speed or other variables

I have a class extended from simple to gesture, and I'm working with the onfling method:

class MyGestureListener extends GestureDetector.SimpleOnGestureListener{ @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { // TODO Auto-generated method stub float e1_X = e1.getX(); float e1_Y = e1.getY(); float e2_X = e1.getX(); float e2_Y = e2.getY(); if(velocityX > 0 && velocityX > velocityY){ text.setText("Swipe left"); }else if(velocityX < 0 && velocityX < velocityY){ text.setText("Swipe right"); }else if(velocityY < 0 && velocityX > velocityY){ text.setText("Swipe down"); }else if(velocityY > 0 && velocityX < velocityY){ text.setText("Swipe up"); } return super.onFling(e1, e2, velocityX, velocityY); } } 

I know that it depends on certain angles, but I can’t do it, I tried with speedX and speedY, it works only if you do it for sure. But what I want is the angle of the β€œerror”: if you swipe diagonally, for example, up and to the right, I need to choose which one is good.

+4
source share
1 answer

You must check the speed and distance. Here is an example of a horizontal subwoofer. You can add vertical detection in the same way.

 public class HSwipeDetector extends SimpleOnGestureListener { private static final int SWIPE_MIN_DISTANCE = 120; private static final int SWIPE_MAX_OFF_PATH = 250; private static final int SWIPE_THRESHOLD_VELOCITY = 200; @Override public boolean onFling(final MotionEvent e1, final MotionEvent e2, final float velocityX, final float velocityY) { if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH) { return false; } /* positive value means right to left direction */ final float distance = e1.getX() - e2.getX(); final boolean enoughSpeed = Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY; if(distance > SWIPE_MIN_DISTANCE && enoughSpeed) { // right to left swipe onSwipeLeft(); return true; } else if (distance < -SWIPE_MIN_DISTANCE && enoughSpeed) { // left to right swipe onSwipeRight(); return true; } else { // oooou, it didn't qualify; do nothing return false; } } protected void onSwipeLeft() { // do your stuff here } protected void onSwipeRight() { // do your stuff here } } 
+4
source

All Articles