Android: How to handle right to left swipe gestures

前端 未结 22 1211
日久生厌
日久生厌 2020-11-21 06:18

I want my app to recognize when a user swipes from right to left on the phone screen.

How to do this?

22条回答
  •  再見小時候
    2020-11-21 07:13

    Kotlin version of @Mirek Rusin is here:

    OnSwipeTouchListener.kt :

    open class OnSwipeTouchListener(ctx: Context) : 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 : 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 (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
            }
    
    
        }
    
        open fun onSwipeRight() {}
    
        open fun onSwipeLeft() {}
    
        open fun onSwipeTop() {}
    
        open fun onSwipeBottom() {}
    }
    

    Usage:

    view.setOnTouchListener(object : OnSwipeTouchListener(context) {
    
        override fun onSwipeTop() {
            super.onSwipeTop()
        }
    
        override fun onSwipeBottom() {
            super.onSwipeBottom()
        }
    
        override fun onSwipeLeft() {
            super.onSwipeLeft()
        }
    
        override fun onSwipeRight() {
            super.onSwipeRight()
        }
    })
    

    the open keyword was the point for me...

提交回复
热议问题