2025-01-17
在build.gradle.kts里面添加依赖
val nav_version = "2.8.5"
// Jetpack Compose integration
implementation("androidx.navigation:navigation-compose:$nav_version")
// Views/Fragments integration
implementation("androidx.navigation:navigation-fragment:$nav_version")
implementation("androidx.navigation:navigation-ui:$nav_version")
// Feature module support for Fragments
implementation("androidx.navigation:navigation-dynamic-features-fragment:$nav_version")
// Testing Navigation
androidTestImplementation("androidx.navigation:navigation-testing:$nav_version")
@Composable
fun MyApp(modifier: Modifier = Modifier){
val navController = rememberNavController()
NavHost(navController = navController, startDestination = "firstScreen"){
composable("firstScreen"){
FirstScreen {
navController.navigate("secondScreen")
}
}
composable("secondScreen"){
SecondScreen {
navController.navigate("firstScreen")
}
}
}
}
navigationToSecondScreen: ()->Unit
@Composable
fun FirstScreen(navigationToSecondScreen: ()->Unit){
var name by remember { mutableStateOf("") }
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text("This is the First Screen", fontSize = 24.sp)
Spacer(modifier = Modifier.height(16.dp))
OutlinedTextField(value = name, onValueChange = {
name = it
})
Button(onClick = {
navigationToSecondScreen()
}) {
Text("Go to Second Screen")
}
}
}