Created
May 7, 2022 18:43
-
-
Save 7kashif/dca27fb9d0574550ae4d3642f60cd8fe to your computer and use it in GitHub Desktop.
Detect left and right swipe on a view.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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