OnSwipeTouchListener.java
1    package com.asimplesock.chatistics;
2    
3    import android.content.Context;
4    import android.view.GestureDetector;
5    import android.view.GestureDetector.SimpleOnGestureListener;
6    import android.view.MotionEvent;
7    import android.view.View;
8    import android.view.View.OnTouchListener;
9    
10   public class OnSwipeTouchListener implements OnTouchListener {
11   
12       private final GestureDetector gestureDetector;
13   
14       public OnSwipeTouchListener (Context ctx){
15           gestureDetector = new GestureDetector(ctx, new GestureListener());
16       }
17   
18       @Override
19       public boolean onTouch(View v, MotionEvent event) {
20           return gestureDetector.onTouchEvent(event);
21       }
22   
23       private final class GestureListener extends SimpleOnGestureListener {
24   
25           private static final int SWIPE_THRESHOLD = 100;
26           private static final int SWIPE_VELOCITY_THRESHOLD = 100;
27   
28           @Override
29           public boolean onDown(MotionEvent e) {
30               return true;
31           }
32   
33           @Override
34           public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
35               boolean result = false;
36               try {
37                   float diffY = e2.getY() - e1.getY();
38                   float diffX = e2.getX() - e1.getX();
39                   if (Math.abs(diffX) > Math.abs(diffY)) {
40                       if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
41                           if (diffX > 0) {
42                               onSwipeRight();
43                           } else {
44                               onSwipeLeft();
45                           }
46                           result = true;
47                       }
48                   }
49                   else if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
50                       if (diffY > 0) {
51                           onSwipeBottom();
52                       } else {
53                           onSwipeTop();
54                       }
55                       result = true;
56                   }
57               } catch (Exception exception) {
58                   exception.printStackTrace();
59               }
60               return result;
61           }
62       }
63   
64       public void onSwipeRight() {
65       }
66   
67       public void onSwipeLeft() {
68       }
69   
70       public void onSwipeTop() {
71       }
72   
73       public void onSwipeBottom() {
74       }
75   }