Skip to content

Instantly share code, notes, and snippets.

@7kashif
Created May 7, 2022 18:43
Show Gist options
  • Save 7kashif/dca27fb9d0574550ae4d3642f60cd8fe to your computer and use it in GitHub Desktop.
Save 7kashif/dca27fb9d0574550ae4d3642f60cd8fe to your computer and use it in GitHub Desktop.
Detect left and right swipe on a view.
class SwipeGestureListener internal constructor(
private val onSwipe: (String) -> Unit,
) : View.OnTouchListener {
companion object {
const val minDistance = 200
}
private var anchorX = 0F
override fun onTouch(view: View, event: MotionEvent): Boolean {
when (event.action) {
MotionEvent.ACTION_DOWN -> {
anchorX = event.x
return true
}
MotionEvent.ACTION_UP -> {
if (abs(event.x - anchorX) > minDistance) {
if (event.x > anchorX) {
onSwipe.invoke("Right")
} else {
onSwipe.invoke("Left")
}
}
return true
}
}
return view.performClick()
}
}
fun View.detectSwipe() {
setOnTouchListener(SwipeGestureListener { swipe->
Log.e("swipeListener",swipe)
}
)
}
//in fragment or activity
binding.YOUR_VIEW.detectSwipe()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment