Skip to content

Instantly share code, notes, and snippets.

@codetgh
Created December 25, 2019 16:17
Show Gist options
  • Save codetgh/6371c8d50fe0c6bc284309a0bd83beec to your computer and use it in GitHub Desktop.
Save codetgh/6371c8d50fe0c6bc284309a0bd83beec to your computer and use it in GitHub Desktop.
class OnSwipeTouchListener(ctx: Context) : View.OnTouchListener {
private val gestureDetector: GestureDetector
private var onSwipeCallback: OnSwipeCallback? = null
private var isViewGroup: Boolean = false
init {
onSwipeCallback = ctx as FlashbackActivityNew
gestureDetector = GestureDetector(ctx, GestureListener())
}
@SuppressLint("ClickableViewAccessibility")
override fun onTouch(v: View, event: MotionEvent?): Boolean {
when (v) {
is RecyclerView -> isViewGroup = false
is AppCompatTextView -> isViewGroup = true
}
return gestureDetector.onTouchEvent(event)
}
private inner class GestureListener : GestureDetector.SimpleOnGestureListener() {
private val SWIPE_THRESHOLD = 100
private val SWIPE_VELOCITY_THRESHOLD = 100
override fun onDown(e: MotionEvent): Boolean {
return isViewGroup
}
override fun onFling(e1: MotionEvent, e2: MotionEvent, velocityX: Float,
velocityY: Float): Boolean {
var result = false
try {
val diffY = e2.y - e1.y
val diffX = e1.x - e2.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()
}
result = true
}
}/* else if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
if (diffY > 0) {
onSwipeBottom()
} else {
onSwipeTop()
}
result = true
}*/
} catch (exception: Exception) {
exception.printStackTrace()
}
return result
}
}
fun onSwipeRight() {
onSwipeCallback?.onSwipeRight()
}
fun onSwipeLeft() {
onSwipeCallback?.onSwipeLeft()
}
/*fun onSwipeTop() {
onSwipeCallback?.onSwipeTop()
}
fun onSwipeBottom() {
onSwipeCallback?.onSwipeBottom()
}*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment