所以我有两个选项卡,选项卡 A 和选项卡 B。每个选项卡都有自己的后台堆栈。我使用这个谷歌文档中的代码实现了多回栈导航
val navController = rememberNavController()
Scaffold(
bottomBar = {
BottomNavigation {
val navBackStackEntry by navController.currentBackStackEntryAsState()
val currentDestination = navBackStackEntry?.destination
items.forEach { screen ->
BottomNavigationItem(
icon = { Icon(Icons.Filled.Favorite, contentDescription = null) },
label = { Text(stringResource(screen.resourceId)) },
selected = currentDestination?.hierarchy?.any { it.route == screen.route } == true,
onClick = {
navController.navigate(screen.route) {
// Pop up to the start destination of the graph to
// avoid building up a large stack of destinations
// on the back stack as users select items
popUpTo(navController.graph.findStartDestination().id) {
saveState = true
}
// Avoid multiple copies of the same destination when
// reselecting the same item
launchSingleTop = true
// Restore state when reselecting a previously selected item
restoreState = true
}
}
)
}
}
}
) {
NavHost(navController, startDestination = A1.route) {
composable(A1.route) {
val viewModelA1 = hiltViewModel()
A1(viewModelA1)
}
composable(A2.route) {
val viewModelA2 = hiltViewModel()
A2(viewModelA2)
}
composable(A3.route) {
val viewModelA3 = hiltViewModel()
A3(viewModelA3)
}
}
}
选项卡 A 有 3 个屏幕(屏幕 A1 -> 屏幕 A2 -> 屏幕 A3)。我使用该函数来实例化视图模型,并在每个屏幕hiltViewModel()
的块内调用它composable()
问题是当我从 A1 导航到 A2 再到 A3 时,然后当我将选项卡更改为选项卡 B 时,屏幕 A2 的视图模型似乎正在被处理(onCleared
被调用)。因此,当我返回显示屏幕 A3 的选项卡 A 然后返回屏幕 A2 时,再次实例化 A2 的视图模型(再次init
调用块)。我想要实现的是为这个流程保留 A2 的视图模型,直到我退出 A2。
这甚至可能吗?