Android: How to handle right to left swipe gestures

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

    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
    
    /**
     * Detects left and right swipes across a view.
     */
    class OnSwipeTouchListener(context: Context, onSwipeCallBack: OnSwipeCallBack?) : OnTouchListener {
    
        private var gestureDetector : GestureDetector
        private var onSwipeCallBack: OnSwipeCallBack?=null
    
        init {
    
            gestureDetector = GestureDetector(context, GestureListener())
            this.onSwipeCallBack = onSwipeCallBack!!
        }
        companion object {
    
            private val SWIPE_DISTANCE_THRESHOLD = 100
            private val SWIPE_VELOCITY_THRESHOLD = 100
        }
    
       /* fun onSwipeLeft() {}
    
        fun onSwipeRight() {}*/
    
        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(eve1: MotionEvent?, eve2: MotionEvent?, velocityX: Float, velocityY: Float): Boolean {
                try {
                    if(eve1 != null&& eve2!= null) {
                        val distanceX = eve2?.x - eve1?.x
                        val distanceY = eve2?.y - eve1?.y
                        if (Math.abs(distanceX) > Math.abs(distanceY) && Math.abs(distanceX) > SWIPE_DISTANCE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
                            if (distanceX > 0)
                                onSwipeCallBack!!.onSwipeLeftCallback()
                            else
                                onSwipeCallBack!!.onSwipeRightCallback()
                            return true
                        }
                    }
                }catch (exception:Exception){
                    exception.printStackTrace()
                }
    
                return false
            }
    
    
        }
    }
    

提交回复
热议问题