在Jetpack Compose中使用Jetpack Navigation导航并传递参数
所属分类:Android | 发布于 2023-03-27 10:52:58
Jetpack Compose本身并没有导航功能,要在Jetpack Compose中实现导航,就要用到Jetpack套件中的Navigation组件。
1、Jetpack Navigation中的几个概念
1.1、NavDestination:页面导航中跳转的各个节点。
1.2、Navigation Graph:Navigation需要收集各个节点之间的跳转关系,因此NavDestination需要集中注册在一起,统一由Graph进行管理。这里面包含了所有的Destination信息,以及可能的跳转路径。
1.3、NavHost:作为容器显示Graph中当前处于栈顶的Destination。比如在Fragment场景中,此容器就是NavHostFragment。
1.4、NavController:执行跳转行为的管理者,它被NavHost所持有,提供了跳转API,调用后,将在NavHost容器完成页面跳转。
2、NavGraph封装
@Composable
fun SetupAppNavGraph(
appState: AppState,
navController: NavHostController,
startDestination: String
) {
NavHost(
navController = navController,
startDestination = startDestination
) {
composable(route = AppScreen.Home.route) {
HomeScreen(appState = appState)
}
composable(route = AppScreen.LoginScreen.route) {
LoginScreen(appState = appState)
}
composable(route = AppScreen.NoteScreen.route) {
NoteScreen(appState = appState)
}
}
}
3、导航传参定义
composable(
route = AppScreen.NoteFormScreen.route + "?noteId={noteId}",
arguments = listOf(
navArgument(name = "noteId") {
type = NavType.IntType
defaultValue = 0
}
)
) {
NoteFormScreen(appState = appState)
}
4、页面接收导航参数
页面接收的方法是通过构造函数将参数传递进去,示例如下:
composable(
route = AppScreen.NoteFormScreen.route + "?noteId={noteId}",
arguments = listOf(
navArgument(name = "noteId") {
type = NavType.IntType
defaultValue = 0
}
)
) { backStackEntry ->
backStackEntry.arguments?.getString("noteId")?.let {
NoteFormScreen(appState = appState, noteId = it)
}
}
@Composable
fun NoteFormScreen(appState: AppState, noteId: Int) {
}
5、在ViewModel中接收导航参数
除了将导航参数作为构造函数参数传递到View之外,还可以通过SavedStateHandle直接在ViewModel中接收参数,
class NoteFromoViewModel(
savedStateHandle: SavedStateHandle
): ViewModel() {
val noteId = savedStateHandle.get<Int>("noteId")
}