Code: Select all
androidx.compose:compose-bom:2024.09.00
Code: Select all
'androidx.compose:compose-bom:2024.09.00'
Code: Select all
val maxWidthPx = constraints.maxWidth.toFloat()
val endPx = maxWidthPx - handleSizePx
val swipeState = remember {
AnchoredDraggableState(
initialValue = false
)
}
LaunchedEffect(endPx, swipeState.currentValue) {
swipeState.updateAnchors(
DraggableAnchors {
if (!swipeState.currentValue) {
false at 0f
}
true at endPx
}
)
}
// Trigger action when the state becomes 'true' (Arrived)
LaunchedEffect(swipeState.currentValue) {
if (swipeState.currentValue) {
onArrived()
Toast.makeText(context, "Arrived", Toast.LENGTH_SHORT).show()
}
}
val flingBehavior = AnchoredDraggableDefaults.flingBehavior(
state = swipeState,
positionalThreshold = { distance -> distance * 0.5f },
animationSpec = spring(
dampingRatio = Spring.DampingRatioLowBouncy,
stiffness = Spring.StiffnessLow
)
)
Box(
modifier = Modifier
.offset {
// Safety check to ensure offset is read only after layout/initialization
val offset = try {
swipeState.requireOffset()
} catch (e: Exception) {
0f
}
IntOffset(offset.roundToInt(), 0)
}
.size(handleSize)
.padding(4.dp)
.clip(CircleShape)
.background(MaterialTheme.colorScheme.primary)
.anchoredDraggable(
state = swipeState,
orientation = Orientation.Horizontal,
flingBehavior = flingBehavior,
),
contentAlignment = Alignment.Center
) {
// My controls
}
Mobile version