1.引入依赖
//jetpack compose导航
implementation("androidx.navigation:navigation-compose:2.5.3")
2.代码
import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.Button import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.sp import androidx.navigation.NavController import androidx.navigation.NavHostController import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavControllerclass MainActivity : ComponentActivity() {private lateinit var mNavController: NavControlleroverride fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContent {//创建导航控制器mNavController = rememberNavController()//创建NavHost导航组建者,传入了mNavController 导航控制器 与 首个显示的页面 startDestination = APageNavHost(navController = mNavController as NavHostController, startDestination = "APage") {//这里添加了页面A,APage为路由地址composable(route = "APage") { APage() }composable(route = "BPage") { BPage() }}}}/*** 页面A*/@Composablefun APage() {Column(Modifier.fillMaxSize(),horizontalAlignment = Alignment.CenterHorizontally,verticalArrangement = Arrangement.Center) {Button(onClick = { mNavController.navigate("BPage") }) {Text(text = "页面A: 点击跳转页面B", fontSize = 30.sp)}}}/*** 页面B*/@Composablefun BPage() {Column(Modifier.fillMaxSize(),horizontalAlignment = Alignment.CenterHorizontally,verticalArrangement = Arrangement.Center) {Button(onClick = { mNavController.navigateUp() }) {Text(text = "页面B: 点击返回页面A", fontSize = 30.sp)}}}}