我的
NavHost
中有以下代码。对于我添加到 enterTransition
的所有路线,都会重复 exitTransition
、popEnterTransition
、popExitTransition
和 NavHost
代码。我该如何清洁它。
NavHost(
navController = navController,
startDestination = CreateProjectRoute,
) {
composable<ProjectsListRoute>(
enterTransition = {
slideIntoContainer(
AnimatedContentTransitionScope.SlideDirection.Left,
tween(500)
)
},
exitTransition = {
slideOutOfContainer(
AnimatedContentTransitionScope.SlideDirection.Left,
tween(500)
)
},
popExitTransition = {
slideOutOfContainer(
AnimatedContentTransitionScope.SlideDirection.Right,
tween(500)
)
},
popEnterTransition = {
slideIntoContainer(
AnimatedContentTransitionScope.SlideDirection.Right,
tween(500)
)
}
) {
ProjectsListScreen(
onCreateButtonClicked = {
navController.navigate(CreateProjectRoute)
}
)
}
composable<CreateProjectRoute>(
enterTransition = {
slideIntoContainer(
AnimatedContentTransitionScope.SlideDirection.Left,
tween(500)
)
},
exitTransition = {
slideOutOfContainer(
AnimatedContentTransitionScope.SlideDirection.Left,
tween(500)
)
},
popExitTransition = {
slideOutOfContainer(
AnimatedContentTransitionScope.SlideDirection.Right,
tween(500)
)
},
popEnterTransition = {
slideIntoContainer(
AnimatedContentTransitionScope.SlideDirection.Right,
tween(500)
)
}
) {
CreateProjectScreen(
viewModel = projectViewModel,
navController = navController
)
}
}
我尝试过创建这样的函数:
fun defaultEnterTransition() = slideIntoContainer(
AnimatedContentTransitionScope.SlideDirection.Left,
tween(500)
)
并在导航路线中使用它们,如下所示:
composable<ProjectsListRoute>(
enterTransition = { defaultEnterTransition() }
) { }
但我收到以下错误:
Unresolved reference: slideIntoContainer
您可以在
NavGraphBuilder
上创建自己的扩展功能,如下所示。
public inline fun <reified T : Any> NavGraphBuilder.slideComposable( typeMap: Map<KType, NavType<*>> = emptyMap(), noinline content: @Composable AnimatedContentScope.(NavBackStackEntry) -> Unit ) { destination( ComposeNavigatorDestinationBuilder( provider[ComposeNavigator::class], T::class, typeMap, content ) .apply { this.enterTransition = { slideIntoContainer( AnimatedContentTransitionScope.SlideDirection.Left, tween(500) ) } this.exitTransition = { slideOutOfContainer( AnimatedContentTransitionScope.SlideDirection.Left, tween(500) ) } this.popEnterTransition = { slideIntoContainer( AnimatedContentTransitionScope.SlideDirection.Right, tween(500) ) } this.popExitTransition = { slideOutOfContainer( AnimatedContentTransitionScope.SlideDirection.Right, tween(500) ) } this.sizeTransform = sizeTransform } ) }
现在您可以使用
slideComposable
代替可组合项。
注意:缺少一些其他参数,例如(深层链接),您可以根据需要添加它。