Jetpack Compose provides powerful gesture detection APIs for building interactive, responsive UIs.
Detecting Taps
@Composable
fun TapDetection() {
var tapCount by remember { mutableStateOf(0) }
Box(
modifier = Modifier
.size(200.dp)
.background(Color.LightGray)
.pointerInput(Unit) {
detectTapGestures(
onTap = { offset ->
tapCount++
},
onDoubleTap = { offset ->
tapCount = 0
}
)
},
contentAlignment = Alignment.Center
) {
Text("Taps: $tapCount")
}
}
Drag and Pan Gestures
@Composable
fun DragGesture() {
var offset by remember { mutableStateOf(Offset.Zero) }
Box(
modifier = Modifier
.size(300.dp)
.background(Color.LightGray)
.pointerInput(Unit) {
detectDragGestures(
onDrag = { change, dragAmount ->
offset += dragAmount
}
)
}
) {
Box(
modifier = Modifier
.size(50.dp)
.background(Color.Red)
.offset(offset.x.dp, offset.y.dp)
)
}
}
Swipe Detection
@Composable
fun SwipeDetection() {
var swipeDirection by remember { mutableStateOf("") }
Box(
modifier = Modifier
.size(200.dp)
.background(Color.LightGray)
.pointerInput(Unit) {
detectHorizontalDragGestures { change, dragAmount ->
swipeDirection = if (dragAmount > 0) "Right" else "Left"
}
},
contentAlignment = Alignment.Center
) {
Text("Swipe: $swipeDirection")
}
}
Multitouch Handling
@Composable
fun MultitouchDetection() {
var touchCount by remember { mutableStateOf(0) }
Box(
modifier = Modifier
.fillMaxSize()
.pointerInput(Unit) {
awaitEachGesture {
val event = awaitPointerEvent()
touchCount = event.changes.size
}
},
contentAlignment = Alignment.Center
) {
Text("Fingers: $touchCount")
}
}
Gesture detection creates intuitive, modern interactions in your app.
8 Android app templates available on Gumroad
Top comments (0)