【发布时间】:2021-10-24 16:21:02
【问题描述】:
我有一个底部栏,在这个可组合的函数中,我想调用我在应用程序导航的导航图中的 ViewModel 中设置的函数,但是想不出任何方法来做到这一点?我玩过一些界面,但我没有得到任何地方
@Composable
fun BottomNavBar(
currentRoute: String?,
navigateToBuild: () -> Unit,
navigateToSaved: () -> Unit
) {
Column() {
Row(modifier = Modifier
.fillMaxWidth()
.height(1.dp)
.background(Color.Gray)) {
}
BottomAppBar(
modifier = Modifier
.height(72.dp),
backgroundColor = Color.White
) {
navItems.forEach { item ->
val selected = currentRoute == item.route
BottomNavigationItem(
icon = {
Image(
painter = painterResource(
id = if (selected) item.selectedIcon else
item.unselectedIcon),
contentDescription = item.title
)
},
selected = selected,
onClick = {
when (item.route) {
NavigationItem.Build.route -> {
navigateToBuild()
}
NavigationItem.Saved.route -> {
navigateToSaved()
// I want to call viewmodel function here
}
}
}
)
}
}
}
}
我的底部栏是这里脚手架的一部分,而我的视图模型在 AppNavigation 组合内,所以它们是完全独立的,我想不出任何方式让它们通信?
Scaffold(
bottomBar = {
BottomNavBar(
currentRoute = currentRoute,
navigateToBuild = { navController.navigate("build/0") },
navigateToSaved = { navController.navigate(DashboardScreens.Saved.route) })
}
) { innerPadding ->
Box(
modifier = Modifier
.padding(innerPadding)
.background(Color.White)
) {
AppNavigation(navHostController = navController)
}
}
【问题讨论】:
-
使用状态调用视图模型中的函数。将状态传递给
AppNavigation -
我认为 Abhimanyu 指的是状态提升,这是声明式 UI 开发中的最佳实践。阅读here。
标签: android android-jetpack-compose