import android.os.Bundle
import android.view.GestureDetector
import android.view.MotionEvent
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
class GestureDemoScreen : AppCompatActivity() {
private lateinit var gestureDetector: GestureDetector
private lateinit var gestureTextView: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_gesture_demo)
gestureTextView = findViewById(R.id.gestureTextView)
val coloredBox = findViewById<ConstraintLayout>(R.id.coloredBox)
gestureDetector = GestureDetector(this, object : GestureDetector.SimpleOnGestureListener() {
override fun onSingleTapConfirmed(e: MotionEvent?): Boolean {
gestureTextView.text = "Tap detected"
return true
}
override fun onFling(
e1: MotionEvent?, e2: MotionEvent?, velocityX: Float, velocityY: Float
): Boolean {
if (e1 == null || e2 == null) return false
val deltaX = e2.x - e1.x
if (Math.abs(deltaX) > 100 && Math.abs(velocityX) > 100) {
if (deltaX > 0) {
gestureTextView.text = "Swipe Right"
} else {
gestureTextView.text = "Swipe Left"
}
return true
}
return false
}
})
coloredBox.setOnTouchListener { _, event ->
gestureDetector.onTouchEvent(event)
true
}
}
}We created a GestureDetector with a listener that detects taps and swipes. The onSingleTapConfirmed method updates the text to "Tap detected" when the user taps the box. The onFling method detects horizontal swipes by checking the difference in X coordinates and velocity, then updates the text to "Swipe Left" or "Swipe Right" accordingly. The colored box forwards all touch events to the gesture detector by setting an onTouchListener. This way, the app responds to user gestures on the box and shows the detected gesture below it.