Navigation
How to use navagation
-
add dependency
implementation "androidx.navigation:navigation-compose:2.5.3" -
using enum or object to distinguish screen.
sample code
enum class LunchTrayScreens(@StringRes val title: Int) {
START(title = R.string.start_order),
ENTREE_MENU(title = R.string.choose_entree),
SIDE_DISH_MENU(title = R.string.choose_side_dish),
ACCOMPANIMENT_MENU(title = R.string.choose_accompaniment),
CHECKOUT(title = R.string.order_summary),
}
<++>
- build Up Navgation host
NavHost
NavHost is responsible for choose screen to display
It basically takes four arguments
modifiernavControllerget it byrememberNavControllerstartLocationinitial screen to displaycontentcompose function- the content is consisted of multiple
composable, each of which is the screen to display composabletakelocationandcontentas its arguments
- the content is consisted of multiple
sample code
NavHost(
navController = naviController,
startDestination = LunchTrayScreens.START.name,
modifier = Modifier.padding(innerPadding)
) {
composable(LunchTrayScreens.START.name) {
StartOrderScreen(onStartOrderButtonClicked = {
naviController.navigate(LunchTrayScreens.ENTREE_MENU.name)
})
}
// ...
}
- build up TopAppbar
sample code
TopAppBar(
modifier = modifier,
title = { Text(text = stringResource(id = currentScreens.title)) },
navigationIcon = {
if (canNavigateBack) {
IconButton(onClick = navigateUp) {
Icon(
imageVector = Icons.Filled.ArrowBack,
contentDescription = stringResource(id = R.string.back_button)
)
}
}
}
)
In main activity
val backStackEntry by naviController.currentBackStackEntryAsState()
// TODO: Get the name of the current screen
val currentScreen = LunchTrayScreens.valueOf(backStackEntry?.destination?.route ?:
LunchTrayScreens.START.name)
-
useful function
-
popstack
navController.popBackStack(LunchTrayScreens.START.name, false) -
返回上一级目录
navController.navigateUp() -
Navigating With arguments
-
发送参数
navController.navigate("${route}"/${id}). Note The the value ofidis specified by you. (act as akeyto get value) -
接受参数
note the brackets
// 接收 一个参数
compose(route = ${route}"/{${id}})
// 接收多个参数
compose(route = ${route}"/{${id}}, arguments = listOf(navArgument(ItemDetailsDestination.itemIdArg) {
type = NavType.IntType }))
viewModel
private val songId: Int = checkNotNull(savedStateHandle["id"])
- using
navigation
composable("profile/{userId}") { backStackEntry ->
Profile(navController, backStackEntry.arguments?.getString("userId"))
}