Android: How to handle right to left swipe gestures

前端 未结 22 1202
日久生厌
日久生厌 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:05

    I've been doing similar things, but for horizontal swipes only

    import android.content.Context
    import android.view.GestureDetector
    import android.view.MotionEvent
    import android.view.View
    
    abstract class OnHorizontalSwipeListener(val context: Context) : View.OnTouchListener {    
    
        companion object {
             const val SWIPE_MIN = 50
             const val SWIPE_VELOCITY_MIN = 100
        }
    
        private val detector = GestureDetector(context, GestureListener())
    
        override fun onTouch(view: View, event: MotionEvent) = detector.onTouchEvent(event)    
    
        abstract fun onRightSwipe()
    
        abstract fun onLeftSwipe()
    
        private inner class GestureListener : GestureDetector.SimpleOnGestureListener() {    
    
            override fun onDown(e: MotionEvent) = true
    
            override fun onFling(e1: MotionEvent, e2: MotionEvent, velocityX: Float, velocityY: Float)
                : Boolean {
    
                val deltaY = e2.y - e1.y
                val deltaX = e2.x - e1.x
    
                if (Math.abs(deltaX) < Math.abs(deltaY)) return false
    
                if (Math.abs(deltaX) < SWIPE_MIN
                        && Math.abs(velocityX) < SWIPE_VELOCITY_MIN) return false
    
                if (deltaX > 0) onRightSwipe() else onLeftSwipe()
    
                return true
            }
        }
    }
    

    And then it can be used for view components

    private fun listenHorizontalSwipe(view: View) {
        view.setOnTouchListener(object : OnHorizontalSwipeListener(context!!) {
                override fun onRightSwipe() {
                    Log.d(TAG, "Swipe right")
                }
    
                override fun onLeftSwipe() {
                    Log.d(TAG, "Swipe left")
                }
    
            }
        )
    }
    

提交回复
热议问题