0
0
Android Kotlinmobile~20 mins

Gesture handling in Android Kotlin - Mini App: Build & Ship

Choose your learning style9 modes available
Build: GestureDemoScreen
This screen detects taps and swipes on a colored box and shows the gesture type below it.
Target UI
┌─────────────────────────────┐
│        Gesture Demo         │
├─────────────────────────────┤
│                             │
│       [ Colored Box ]        │
│                             │
│                             │
│  Gesture detected: None     │
│                             │
└─────────────────────────────┘
Display a colored box in the center of the screen.
Detect tap gestures on the box and update text below to 'Tap detected'.
Detect swipe gestures (left or right) on the box and update text to 'Swipe Left' or 'Swipe Right'.
Use Android GestureDetector for gesture detection.
Text below the box shows the last detected gesture or 'None' initially.
Starter Code
Android Kotlin
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)

        // TODO: Initialize gestureDetector with a GestureListener
        // TODO: Set touch listener on coloredBox to pass events to gestureDetector
    }
}
Task 1
Task 2
Task 3
Task 4
Solution
Android Kotlin
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.

Final Result
Completed Screen
┌─────────────────────────────┐
│        Gesture Demo         │
├─────────────────────────────┤
│                             │
│       [ Colored Box ]        │
│                             │
│                             │
│  Gesture detected: Tap detected  │
│                             │
└─────────────────────────────┘
When user taps the colored box, the text below changes to 'Tap detected'.
When user swipes left on the box, the text changes to 'Swipe Left'.
When user swipes right on the box, the text changes to 'Swipe Right'.
Stretch Goal
Add detection for long press gesture and update the text to 'Long press detected'.
💡 Hint
Override the onLongPress method in GestureDetector.SimpleOnGestureListener and update the TextView text.