Created
March 16, 2021 19:06
-
-
Save pauloaapereira/9d07cef1b5da0346553c69d24cdc2743 to your computer and use it in GitHub Desktop.
Jetpack Compose — Drawer Pushing Content - 7
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
@Composable | |
fun DrawerContainer( | |
modifier: Modifier = Modifier, | |
isDrawerOpened: Boolean = false, | |
drawerWidth: Dp = 200.dp, | |
onSwipe: (Boolean) -> Unit = {}, | |
content: @Composable () -> Unit | |
) { | |
val transition = updateTransition(targetState = isDrawerOpened) | |
val collapseFraction = | |
transition.animateFloat(transitionSpec = { tween(durationMillis = 400) }) { state -> | |
when (state) { | |
false -> 0f | |
true -> 1f | |
} | |
} | |
Layout( | |
modifier = modifier.pointerInput(Unit) { | |
detectHorizontalDragGestures { _, dragAmount -> | |
if (!transition.isRunning) { | |
onSwipe(dragAmount > 0 && abs(dragAmount) > 15) | |
} | |
} | |
}, | |
content = content | |
) { measurables, constraints -> | |
val drawerPlaceable = runCatching { | |
measurables[0].measure( | |
Constraints.fixed( | |
drawerWidth.roundToPx(), | |
constraints.maxHeight | |
) | |
) | |
}.getOrNull() | |
val contentPlaceable = runCatching { measurables[1].measure(constraints) }.getOrNull() | |
val drawerX = MathUtils.lerp( | |
-drawerWidth.roundToPx().toFloat(), | |
0.dp.roundToPx().toFloat(), | |
collapseFraction.value | |
).roundToInt() | |
val contentX = MathUtils.lerp( | |
0.dp.roundToPx().toFloat(), | |
drawerWidth.roundToPx().toFloat(), | |
collapseFraction.value | |
).roundToInt() | |
layout( | |
width = constraints.maxWidth, | |
height = constraints.maxHeight | |
) { | |
drawerPlaceable?.place(x = drawerX, y = 0) | |
contentPlaceable?.place(x = contentX, y = 0) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment