Created
October 6, 2023 10:10
-
-
Save wing-tree/dfc08c85c275f5324acc3eedb24c93f3 to your computer and use it in GitHub Desktop.
Android Jetpack Compose SwipeToReveal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
enum class RevealValue { | |
Hidden, | |
Revealed | |
} | |
class RevealState( | |
revealedWidth: Float, | |
positionalThreshold: (Float) -> Float = { | |
it.times(0.5f) | |
}, | |
velocityThreshold: () -> Float = { | |
100.dp.value | |
} | |
) { | |
@OptIn(ExperimentalFoundationApi::class) | |
val anchors = DraggableAnchors { | |
RevealValue.Hidden at 0f | |
RevealValue.Revealed at revealedWidth | |
} | |
@OptIn(ExperimentalFoundationApi::class) | |
val anchoredDraggableState = AnchoredDraggableState( | |
initialValue = RevealValue.Hidden, | |
anchors = anchors, | |
positionalThreshold = positionalThreshold, | |
velocityThreshold = velocityThreshold, | |
animationSpec = spring() | |
).apply { | |
updateAnchors(anchors) | |
} | |
@OptIn(ExperimentalFoundationApi::class) | |
fun requireOffset() = anchoredDraggableState.requireOffset() | |
} | |
@OptIn(ExperimentalFoundationApi::class) | |
@Composable | |
fun SwipeToReveal( | |
state: RevealState, | |
foreground: @Composable RowScope.() -> Unit, | |
revealContent: @Composable RowScope.() -> Unit, | |
modifier: Modifier = Modifier, | |
reverseDirection: Boolean = false, | |
) { | |
Box( | |
modifier = modifier.anchoredDraggable( | |
state = state.anchoredDraggableState, | |
orientation = Orientation.Horizontal, | |
reverseDirection = reverseDirection | |
) | |
) { | |
Row( | |
content = revealContent, | |
modifier = Modifier.matchParentSize() | |
) | |
Row( | |
content = foreground, | |
modifier = Modifier | |
.offset { | |
IntOffset( | |
state | |
.requireOffset() | |
.roundToInt() | |
.let { | |
if (reverseDirection) { | |
it.unaryMinus() | |
} else { | |
it | |
} | |
}, 0 | |
) | |
} | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment