Enable swipe gestures between a set of predefined states.
SwipeableSample
@Composable
@OptIn(ExperimentalMaterialApi::class)
fun SwipeableSample() {
// Draw a slider-like composable consisting of a red square moving along a
// black background, with three states: "A" (min), "B" (middle), and "C" (max).
val width = 350.dp
val squareSize = 50.dp
val swipeableState = rememberSwipeableState("A")
val sizePx = with(LocalDensity.current) { (width - squareSize).toPx() }
val anchors = mapOf(0f to "A", sizePx / 2 to "B", sizePx to "C")
Box(
modifier =
Modifier.width(width)
.swipeable(
state = swipeableState,
anchors = anchors,
thresholds = { _, _ -> FractionalThreshold(0.5f) },
orientation = Orientation.Horizontal,
)
.background(Color.Black)
) {
Box(
Modifier.offset { IntOffset(swipeableState.offset.value.roundToInt(), 0) }
.size(squareSize)
.background(Color.Red),
contentAlignment = Alignment.Center,
) {
Text(swipeableState.currentValue, color = Color.White, fontSize = 24.sp)
}
}
}