Last active
August 29, 2022 12:31
-
-
Save vanniktech/2dc4bfa6315ceff348547d9d04a57563 to your computer and use it in GitHub Desktop.
Android Swipe Left / Right
This file contains hidden or 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
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 | |
import timber.log.Timber | |
import kotlin.math.abs | |
interface OnSwipeDelegate { | |
fun onSwipeRight(): Boolean = false | |
fun onSwipeLeft(): Boolean = false | |
fun onSwipeUp(): Boolean = false | |
fun onSwipeDown(): Boolean = false | |
} | |
fun View.setOnSwipe(delegate: OnSwipeDelegate) { | |
setOnTouchListener(OnSwipeTouchListener(context, delegate)) | |
} | |
private class OnSwipeTouchListener( | |
context: Context, | |
private val delegate: OnSwipeDelegate, | |
) : SimpleOnGestureListener(), OnTouchListener { | |
companion object { | |
private const val SwipeThreshold = 100 | |
private const val SwipeVelocityThreshold = 100 | |
} | |
private val gestureDetector = GestureDetector(context, this) | |
@SuppressLint("ClickableViewAccessibility") | |
override fun onTouch(v: View, event: MotionEvent): Boolean = gestureDetector.onTouchEvent(event) | |
override fun onDown(e: MotionEvent) = true | |
override fun onFling( | |
e1: MotionEvent, | |
e2: MotionEvent, | |
velocityX: Float, | |
velocityY: Float, | |
): Boolean { | |
try { | |
val diffY = e2.y - e1.y | |
val diffX = e2.x - e1.x | |
if (abs(diffX) > abs(diffY)) { | |
if (abs(diffX) > SwipeThreshold && abs(velocityX) > SwipeVelocityThreshold) { | |
return when { | |
diffX > 0 -> delegate.onSwipeRight() | |
else -> delegate.onSwipeLeft() | |
} | |
} | |
} else if (abs(diffY) > SwipeThreshold && abs(velocityY) > SwipeVelocityThreshold) { | |
return when { | |
diffY > 0 -> delegate.onSwipeDown() | |
else -> delegate.onSwipeUp() | |
} | |
} | |
} catch (exception: Exception) { | |
Timber.w(exception) | |
} | |
return false | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment