Advertisement
ridjis

OnSwipeTouchListener

Oct 24th, 2015
372
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.53 KB | None | 0 0
  1. import android.view.GestureDetector;
  2. import android.view.MotionEvent;
  3. import android.view.View;
  4.  
  5. public class OnSwipeTouchListener implements View.OnTouchListener {
  6.     private final GestureDetector gd = new GestureDetector(new GestureListener());
  7.  
  8.     @Override
  9.     public boolean onTouch(View v, MotionEvent event) {
  10.         return gd.onTouchEvent(event);
  11.     }
  12.  
  13.     private final class GestureListener extends GestureDetector.SimpleOnGestureListener {
  14.         private static final int SWIPE_THRESHOLD = 100;
  15.         private static final int SWIPE_VELOCITY_THRESHOLD = 100;
  16.  
  17.         @Override
  18.         public boolean onDown(MotionEvent e) {
  19.             return true;
  20.         }
  21.         @Override
  22.         public boolean onSingleTapConfirmed(MotionEvent e) {
  23.             onClick();
  24.             return true;
  25.         }
  26.  
  27.         @Override
  28.         public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
  29.             float diffX = e2.getX() - e1.getX();
  30.             try {
  31.                 if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
  32.                     if  (diffX > 0) {
  33.                         onSwipeRight();
  34.                     } else {
  35.                         onSwipeLeft();
  36.                     }
  37.                 }
  38.             } catch (Exception e) {
  39.                 e.printStackTrace();
  40.             }
  41.             return true;
  42.         }
  43.     }
  44.  
  45.     public void onSwipeRight() {}
  46.     public void onSwipeLeft() {}
  47.     public void onClick() {}
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement