0

Have to give swipe left and right gesture for buttons. I've used GestureDetector to detect onFling and it was working on android 9 and below versions. From android 10 and above by default swipe left/right will go to previous screen. How to disable default swipe gesture.

open class SwipeTouchListener(ctx: Context) : View.OnTouchListener {

private val gestureDetector: GestureDetector

companion object {

    private val SWIPE_THRESHOLD = 100
    private val SWIPE_VELOCITY_THRESHOLD = 100
}

init {
    gestureDetector = GestureDetector(ctx, GestureListener())
}

override fun onTouch(v: View, event: MotionEvent): Boolean {
    return gestureDetector.onTouchEvent(event)
}

private inner class GestureListener : GestureDetector.SimpleOnGestureListener() {


    override fun onDown(e: MotionEvent): Boolean {
        return true
    }

    override fun onFling(
        e1: MotionEvent,
        e2: MotionEvent,
        velocityX: Float,
        velocityY: Float
    ): Boolean {
        var result = false
        try {
            val diffY = e2.y - e1.y
            val diffX = e2.x - e1.x
            if (abs(diffX) > abs(diffY)) {
                if (abs(diffX) > SWIPE_THRESHOLD && abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
                    if (diffX > 0) {
                        onSwipeRight()
                    } else {
                        onSwipeLeft()
                    }
                    result = true
                }
            } else if (abs(diffY) > SWIPE_THRESHOLD && abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
                if (diffY > 0) {
                    onSwipeBottom()
                } else {
                    onSwipeTop()
                }
                result = true
            }
        } catch (exception: Exception) {
            exception.printStackTrace()
        }

        return result
    }


}

open fun onSwipeRight() {}

open fun onSwipeLeft() {}

open fun onSwipeTop() {}

open fun onSwipeBottom() {}

}

Kamal
  • 1,051
  • 1
  • 11
  • 24
  • 1
    "From android 10 and above by default swipe left/right will go to previous screen" -- only if the user has enabled gesture navigation and AFAIK only if it is a bezel swipe (i.e., in from the edges). You can use https://developer.android.com/develop/ui/views/layout/edge-to-edge?hl=en#system-gesture-insets to find out where the system gestures take precedence over your app and move your buttons to avoid those areas. – CommonsWare Nov 25 '22 at 15:21

0 Answers0