Skip to content

Instantly share code, notes, and snippets.

@djnotes
Last active May 18, 2022 08:24
Show Gist options
  • Save djnotes/789be4b31a68e48caeba0554e489b371 to your computer and use it in GitHub Desktop.
Save djnotes/789be4b31a68e48caeba0554e489b371 to your computer and use it in GitHub Desktop.
A small sample showing the use of swipeable Modifier in Jetpack Compose
@Composable
fun SwipeableSample(){
//Adapted from original Android CS sample https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:compose/material/material/samples/src/main/java/androidx/compose/material/samples/SwipeableSamples.kt
// 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 = 300.dp
val squareSize = 100.dp
val swipeState = rememberSwipeableState(Machine.Off)
val lengthPx = with(LocalDensity.current) { (width - squareSize).toPx() }
val anchors = mapOf(0f to Machine.Off, lengthPx to Machine.On)
val switchColor = animateColorAsState(if(swipeState.currentValue == Machine.Off) Color.Gray else Color.Red)
.value
Box(
modifier = Modifier
.width(width)
.height(squareSize)
.swipeable(
state = swipeState,
anchors = anchors,
thresholds = { _, _ -> FractionalThreshold(0.5f) },
orientation = Orientation.Horizontal
)
.border(1.dp, Color.Black, RoundedCornerShape(4.dp))
) {
Box(
Modifier
.offset { IntOffset(swipeState.offset.value.roundToInt(), 0) }
.size(squareSize)
.background(
switchColor,
RoundedCornerShape(4.dp)
)
.border(1.dp, switchColor, RoundedCornerShape(4.dp))
,
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment