1package com.cheogram.android;
2
3import android.util.Log;
4import android.view.MotionEvent;
5import android.view.View;
6
7import androidx.core.util.Consumer;
8
9// https://stackoverflow.com/a/41766670/8611
10/**
11 * Created by hoshyar on 1/19/17.
12 */
13
14public class SwipeDetector implements View.OnTouchListener {
15
16 protected Consumer<Action> cb;
17 public SwipeDetector(Consumer<Action> cb) {
18 this.cb = cb;
19 }
20
21 public static enum Action {
22 LR, // Left to Right
23 RL, // Right to Left
24 TB, // Top to bottom
25 BT, // Bottom to Top
26 None // when no action was detected
27 }
28
29 private static final String logTag = "Swipe";
30 private static final int MIN_DISTANCE = 100;
31 private float downX, downY, upX, upY;
32 private Action mSwipeDetected = Action.None;
33
34 public boolean swipeDetected() {
35 return mSwipeDetected != Action.None;
36 }
37
38 public Action getAction() {
39 return mSwipeDetected;
40 }
41
42 @Override
43 public boolean onTouch(View v, MotionEvent event) {
44 switch (event.getAction()) {
45 case MotionEvent.ACTION_DOWN:
46 downX = event.getX();
47 downY = event.getY();
48 mSwipeDetected = Action.None;
49 return false;
50
51 case MotionEvent.ACTION_MOVE:
52 upX = event.getX();
53 upY = event.getY();
54
55 float deltaX = downX - upX;
56 float deltaY = downY - upY;
57
58 if (Math.abs(deltaY) < 15 && deltaX < -15) {
59 v.getParent().requestDisallowInterceptTouchEvent(true);
60 }
61
62 if (Math.abs(deltaX) > MIN_DISTANCE) {
63 // left or right
64 if (deltaX < 0) {
65 cb.accept(mSwipeDetected = Action.LR);
66 return false;
67 }
68 if (deltaX > 0) {
69 cb.accept(mSwipeDetected = Action.RL);
70 return false;
71 }
72 } else if (Math.abs(deltaY) > MIN_DISTANCE) {
73 if (deltaY < 0) {
74 cb.accept(mSwipeDetected = Action.TB);
75 return false;
76 }
77 if (deltaY > 0) {
78 cb.accept(mSwipeDetected = Action.BT);
79 return false;
80 }
81 }
82 return false;
83 }
84 return false;
85 }
86}