Skip to content

Instantly share code, notes, and snippets.

@Barros9
Created July 10, 2022 08:28
Show Gist options
  • Save Barros9/8db9edd138edb26eb48a4ccb29335eed to your computer and use it in GitHub Desktop.
Save Barros9/8db9edd138edb26eb48a4ccb29335eed to your computer and use it in GitHub Desktop.
SwipeButton
fun SwipeButton(
modifier: Modifier = Modifier,
shape: Shape = RoundedCornerShape(16.dp),
backgroundColor: Color = Color.White,
borderStroke: BorderStroke = BorderStroke(2.dp, Color.Black),
elevation: Dp = 8.dp,
icon: @Composable () -> Unit,
text: String,
textStyle: TextStyle = TextStyle(Color.Black, 20.sp),
onSwipe: () -> Unit
) {
val swipeableState = rememberSwipeableState(initialValue = 0)
val textAlpha by animateFloatAsState(
if (swipeableState.offset.value > 10f) (1 - swipeableState.progress.fraction) else 1f
)
if (swipeableState.isAnimationRunning) {
DisposableEffect(Unit) {
onDispose {
if (swipeableState.currentValue == 1) {
onSwipe()
}
}
}
}
Surface(
modifier = modifier.fillMaxWidth(),
shape = shape,
color = backgroundColor,
border = borderStroke,
elevation = elevation
) {
BoxWithConstraints(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
) {
var iconSize by remember { mutableStateOf(IntSize.Zero) }
val maxWidth = with(LocalDensity.current) {
[email protected]() - iconSize.width
}
Text(
modifier = Modifier
.fillMaxWidth()
.align(Alignment.Center),
textAlign = TextAlign.End,
text = text,
style = textStyle.copy(color = textStyle.color.copy(alpha = textAlpha))
)
Box(
modifier = Modifier
.onGloballyPositioned {
iconSize = it.size
}
.swipeable(
state = swipeableState,
anchors = mapOf(
0f to 0,
maxWidth to 1
),
thresholds = { _, _ -> FractionalThreshold(0.9f) },
orientation = Orientation.Horizontal
)
.offset {
IntOffset(swipeableState.offset.value.roundToInt(), 0)
}
) {
icon()
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment