Compose Modifier

draggable

Configure touch dragging for the UI element in a single Orientation.

DraggableSample

@Sampled
@Composable
fun DraggableSample() {
    // Draw a seekbar-like composable that has a black background
    // with a red square that moves along the 300.dp drag distance
    val max = 300.dp
    val min = 0.dp
    val (minPx, maxPx) = with(LocalDensity.current) { min.toPx() to max.toPx() }
    // this is the  state we will update while dragging
    val offsetPosition = remember { mutableStateOf(0f) }

    // seekbar itself
    Box(
        modifier =
            Modifier.width(max)
                .draggable(
                    orientation = Orientation.Horizontal,
                    state =
                        rememberDraggableState { delta ->
                            val newValue = offsetPosition.value + delta
                            offsetPosition.value = newValue.coerceIn(minPx, maxPx)
                        },
                )
                .background(Color.Black)
    ) {
        Box(
            Modifier.offset { IntOffset(offsetPosition.value.roundToInt(), 0) }
                .size(50.dp)
                .background(Color.Red)
        )
    }
}
Jetpack Compose beyond MaterialFree components, screens and templates for apps that don’t look like Google’s. Copy them into your app, or let your coding agent add them.Browse for free

Content updated: