帮我写一个JetPack Compose Navigation转场动画
时间: 2023-05-17 18:03:34 浏览: 160
当然可以,以下是一个简单的 JetPack Compose Navigation 转场动画的示例代码:
```kotlin
@Composable
fun NavigationAnimation(navController: NavHostController) {
val transition = updateTransition(targetState = navController.currentBackStackEntry?.destination?.route)
val offset by transition.animateDp(
transitionSpec = {
slideInHorizontally(
initialOffsetX = { -it },
animationSpec = tween(durationMillis = 300)
) with slideOutHorizontally(
targetOffsetX = { it },
animationSpec = tween(durationMillis = 300)
)
}
) { route ->
when (route) {
"Screen1" -> 0.dp
"Screen2" -> 100.dp
else -> 0.dp
}
}
NavHost(navController, startDestination = "Screen1") {
composable("Screen1") {
Screen1()
}
composable("Screen2") {
Screen2()
}
}
}
@Composable
fun Screen1() {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Text(text = "Screen 1")
}
}
@Composable
fun Screen2() {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Text(text = "Screen 2")
}
}
```
在这个示例中,我们使用 `updateTransition` 和 `animateDp` 来创建一个简单的水平滑动转场动画。我们还使用 `NavHost` 和 `composable` 来定义导航栏和屏幕。最后,我们将 `NavHost` 和 `NavHostController` 传递给 `NavigationAnimation` 函数,以便在屏幕之间进行导航。
阅读全文