Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

megamindjoker commented Dec 9, 2016

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

fernandospr commented Sep 29, 2018

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

Yuhanlolo commented Jan 12, 2019

How to make it work in Fragment?

@DanielJette
Copy link

DanielJette commented May 29, 2019

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

@nesquena
Copy link
Author

nesquena commented May 29, 2019

@DanielJette added an MIT license now

@DanielJette
Copy link

DanielJette commented May 30, 2019

Thank you!

@chamampi
Copy link

chamampi commented Oct 22, 2020

Gracias

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