Custom swipeable switch in Jetpack Compose

Viewed 33

I want to do custom swipeable switch, but I want the switch to be only swiped from the main part (the dark grey box). The problem is that I can swipe the box from anywhere, even the light gray part(when the dark grey box is in the other side) in the row. How can I make it to get gestures only from dark grey box.

val width = 96.dp
val squareSize = 48.dp

val swipeableState = rememberSwipeableState(0)
val sizePx = with(LocalDensity.current) { squareSize.toPx() }
val anchors = mapOf(0f to 0, sizePx to 1) // Maps anchor points (in px) to states

Box(
    modifier = Modifier
        .width(width)
        .swipeable(
            state = swipeableState,
            anchors = anchors,
            thresholds = { _, _ -> FractionalThreshold(0.3f) },
            orientation = Orientation.Horizontal
        )
        .background(Color.LightGray)
) {
    Box(
        Modifier
            .offset { IntOffset(swipeableState.offset.value.roundToInt(), 0) }
            .size(squareSize)
            .background(Color.DarkGray)
    )
}
1 Answers

Move swipeable modifier to inner Box

Box(
    modifier = Modifier
        .width(width)
       
        .background(Color.LightGray)
) {
    Box(
        Modifier
            .swipeable(
            state = swipeableState,
            anchors = anchors,
            thresholds = { _, _ -> FractionalThreshold(0.3f) },
            orientation = Orientation.Horizontal
        )
            .offset { IntOffset(swipeableState.offset.value.roundToInt(), 0) }
            .size(squareSize)
            .background(Color.DarkGray)
    )
}
Related