@Composable
fun AppPage() {
val navController = rememberNavController()
//first way
Page1(navController)
//second way
Page3 {
navController.navigate("AnyRoute")
}
}
@Composable
fun Page1(navController: NavHostController) {
//do anything
Page2(navController = navController)
}
@Composable
fun Page2(navController: NavHostController) {
navController.navigate("AnyRoute")
}
@Composable
fun Page3(toLogin: () -> Unit) {
//do anything
Page4 {
toLogin.invoke()
}
}
@Composable
fun Page4(toLogin: () -> Unit) {
Text(text = "test", modifier = Modifier.clickable {
toLogin.invoke()
})
}
我觉得这两种方法都不是很好。两者都容易导致方法中的参数过多,尤其是第二种,感觉很麻烦。使用navigation导航有没有什么好的方法
这就是我导航的方式。我尽力将它应用到你的例子中。
In your Main Activity. Pass to the Navigator any parameters your screens will need such as viewModels.
val navController = rememberNavController()
Navigator(navController, toLogin: () -> Unit)
Create a file like below with an object for each screen you want.
sealed class Screens(val route: String) {
object Page1: Screens("Page1")
object Page2: Screens("Page2")
object Page3: Screens("Page3")
object Page4: Screens("Page4")
}
Create a composable as follows. The startDestination is what screen the app will open to when started.
@Composable
fun Navigator (navController: NavHostController,
) {
NavHost(
navController = navController,
startDestination = Screens.Page1.route)
{
composable(route = Screens.Page1.route){
Page1(viewModel, navController)
}
composable(route = Screens.Page2.route){
Page2(viewModel, navController)
}
composable(route = Screens.Page3.route){
Page3(viewModel, navController)
}
composable(route = Screens.Page4.route){
Page4(viewModel, navController)
}
}
}
From any of your composables you can navigate to another with this.
navController.navigate(Screens.Page3.route)