Skip to content

Instantly share code, notes, and snippets.

@nesquena
Last active November 27, 2021 09:32
Show Gist options
  • Star 45 You must be signed in to star a gist
  • Fork 11 You must be signed in to fork a gist
  • Save nesquena/ed58f34791da00da9751 to your computer and use it in GitHub Desktop.
Save nesquena/ed58f34791da00da9751 to your computer and use it in GitHub Desktop.
Android Swipe Gesture Detector
/*
Usage:
myView.setOnTouchListener(new OnSwipeTouchListener(this) {
@Override
public void onSwipeDown() {
Toast.makeText(MainActivity.this, "Down", Toast.LENGTH_SHORT).show();
}
}
*/
public class OnSwipeTouchListener implements OnTouchListener {
private GestureDetector gestureDetector;
public OnSwipeTouchListener(Context c) {
gestureDetector = new GestureDetector(c, new GestureListener());
}
public boolean onTouch(final View view, final MotionEvent motionEvent) {
return gestureDetector.onTouchEvent(motionEvent);
}
private final class GestureListener extends SimpleOnGestureListener {
private static final int SWIPE_THRESHOLD = 100;
private static final int SWIPE_VELOCITY_THRESHOLD = 100;
@Override
public boolean onDown(MotionEvent e) {
return true;
}
// Determines the fling velocity and then fires the appropriate swipe event accordingly
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
boolean result = false;
try {
float diffY = e2.getY() - e1.getY();
float diffX = e2.getX() - e1.getX();
if (Math.abs(diffX) > Math.abs(diffY)) {
if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
if (diffX > 0) {
onSwipeRight();
} else {
onSwipeLeft();
}
}
} else {
if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
if (diffY > 0) {
onSwipeDown();
} else {
onSwipeUp();
}
}
}
} catch (Exception exception) {
exception.printStackTrace();
}
return result;
}
}
public void onSwipeRight() {
}
public void onSwipeLeft() {
}
public void onSwipeUp() {
}
public void onSwipeDown() {
}
}

MIT License

Copyright (c) 2019 Nathan Esquenazi

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

@megamindjoker
Copy link

Nice yo
thank you alot :D

@varunchandran333
Copy link

varunchandran333 commented Apr 23, 2018

myView.setOnTouchListener(new OnSwipeTouchListener(this) {
@OverRide
public void onSwipeDown() {
Toast.makeText(MainActivity.this, "Down", Toast.LENGTH_SHORT).show();
}
}

How can it be done in kotlin??

@fernandospr
Copy link

In Kotlin:

/*

Usage:
    myView.setOnTouchListener(object: OnSwipeTouchListener(this@MainActivity) {
      override fun onSwipeDown() {
        Toast.makeText(this@MainActivity, "Down", Toast.LENGTH_SHORT).show();
      }
    })

*/

import android.annotation.SuppressLint
import android.content.Context
import android.view.GestureDetector
import android.view.GestureDetector.SimpleOnGestureListener
import android.view.MotionEvent
import android.view.View
import android.view.View.OnTouchListener

open class OnSwipeTouchListener(c: Context) : OnTouchListener {

  companion object {
    private const val SWIPE_THRESHOLD = 100
    private const val SWIPE_VELOCITY_THRESHOLD = 100
  }

  private val gestureDetector: GestureDetector

  init {
    gestureDetector = GestureDetector(c, GestureListener())
  }

  @SuppressLint("ClickableViewAccessibility")
  override fun onTouch(view: View, motionEvent: MotionEvent): Boolean {
    return gestureDetector.onTouchEvent(motionEvent)
  }

  private inner class GestureListener : SimpleOnGestureListener() {

    override fun onDown(e: MotionEvent): Boolean {
      return true
    }

    // Determines the fling velocity and then fires the appropriate swipe event accordingly
    override fun onFling(e1: MotionEvent, e2: MotionEvent, velocityX: Float, velocityY: Float): Boolean {
      val result = false
      try {
        val diffY = e2.y - e1.y
        val diffX = e2.x - e1.x
        if (Math.abs(diffX) > Math.abs(diffY)) {
          if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
            if (diffX > 0) {
              onSwipeRight()
            } else {
              onSwipeLeft()
            }
          }
        } else {
          if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
            if (diffY > 0) {
              onSwipeDown()
            } else {
              onSwipeUp()
            }
          }
        }
      } catch (exception: Exception) {
        exception.printStackTrace()
      }

      return result
    }
  }

  open fun onSwipeRight() {}

  open fun onSwipeLeft() {}

  open fun onSwipeUp() {}

  open fun onSwipeDown() {}
}

@Yuhanlolo
Copy link

How to make it work in Fragment?

@DanielJette
Copy link

Thanks for posting this @nesquena. Are you sharing this under any particular license agreement?

@nesquena
Copy link
Author

@DanielJette added an MIT license now

@DanielJette
Copy link

Thank you!

@chamampi
Copy link

Gracias

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment