在 Android jetpack 中撰写 我必须导航到具有视图模型和状态的屏幕。 我不想使用对话框,因为它使我的架构变得复杂
那么如何从第一个屏幕导航到第二个屏幕,它重叠在第一个屏幕的顶部,而不是替换它?
这就是chatGPT 给我的。但它不起作用
@Composable
fun FirstScreen(navController: NavController) {
Column {
Text(text = "This is the first screen")
Button(onClick = { navController.navigate("second") }) {
Text(text = "Go to second screen")
}
}
}
@Composable
fun SecondScreen(navController: NavController) {
Dialog(onDismissRequest = { navController.popBackStack() }) {
Text(text = "This is the second screen")
}
}
@Composable
fun MyApp() {
val navController = rememberNavController()
NavHost(navController = navController, startDestination = "first") {
composable("first") { FirstScreen(navController) }
composable("second") { SecondScreen(navController) }
}
}
您可以在
dialog
中使用
composable
代替
NavHost
这是当前示例中的代码
@Preview
@Composable
fun MyApp() {
val navController = rememberNavController()
NavHost(navController = navController, startDestination = "first") {
composable("first") { FirstScreen(navController) }
dialog("second") { SecondScreen(navController) }
}
}
@Composable
fun FirstScreen(navController: NavController) {
Column(
Modifier
.fillMaxSize()
.background(Color.Blue), verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(text = "This is the first screen")
Button(onClick = { navController.navigate("second") }) {
Text(text = "Go to second screen")
}
}
}
@Composable
fun SecondScreen(navController: NavController) {
Column(Modifier.background(Color.Red.copy(alpha = 0.1f))) {
Text(text = "This is the second screen")
Button(onClick = { navController.popBackStack() }) {
Text(text = "Go back")
}
}
}