我正在使用伴奏中的导航动画
有以下使用方法
AnimatedNavHost(navController, startDestination, Modifier.padding(paddingValues)) {
composable("greet",
enterTransition = { // push
slideIntoContainer(AnimatedContentScope.SlideDirection.Left, animationSpec = tween(400))
},
popExitTransition = { // pop
slideOutOfContainer(AnimatedContentScope.SlideDirection.Right, animationSpec = tween(300))
},
exitTransition = {
slideOutOfContainer(AnimatedContentScope.SlideDirection.Left, animationSpec = tween(400))
},
popEnterTransition = {
slideIntoContainer(AnimatedContentScope.SlideDirection.Right, animationSpec = tween(350))
}
) { GreetView(navController) }
}
由于可组合的定义都相同,我如何重用可组合。
简化如下:
AnimatedNavHost() {
composable("greet") {
// ...
}
}
您可以使用接收器 NavGraphBuilder
创建一个扩展函数,您可以在其中预填充所有过渡,只需添加将要更改的部分。
这是根据您的问题举个例子。
@OptIn(ExperimentalAnimationApi::class)
fun NavGraphBuilder.composable(
route: String,
content: @Composable () -> Unit,
) {
val enterTransition =
slideIntoContainer(AnimatedContentScope.SlideDirection.Left, animationSpec = tween(400))
val exitTransition =
slideOutOfContainer(AnimatedContentScope.SlideDirection.Left, animationSpec = tween(400))
val popExitTransition =
slideOutOfContainer(AnimatedContentScope.SlideDirection.Right, animationSpec = tween(300))
val popEnterTransition =
slideIntoContainer(AnimatedContentScope.SlideDirection.Right, animationSpec = tween(350))
composable(
route = route,
enterTransition = { _, _ ->
enterTransition
},
popEnterTransition = { _, _ ->
popEnterTransition
},
popExitTransition = { _, _ ->
popExitTransition
},
exitTransition = { _, _ ->
exitTransition
}
) {
content()
}
}
现在,您可以继续从导航图中使用它作为,
composable("greet"){
}
当您从导航图中键入可组合
图形时,Android Studio 可能会尝试使用默认的导航图,因此您应该确保改用扩展函数。为了简化它,您可以将扩展函数从可组合
重命名为其他名称。