跳到主要内容

使用 Compose 进行导航

参考:使用 Compose 进行导航 | Jetpack Compose | Android Developers

添加依赖

修改 gradle/libs.versions.toml 文件,添加以下内容:

gradle/libs.versions.toml
[versions]
navigation = "2.7.7"

[libraries]
androidx-navigation = { module = "androidx.navigation:navigation-compose", version.ref = "navigation" }

修改 build.gradle.kts 文件,添加以下内容:

build.gradle.kts
dependencies {
// val nav_version = "2.7.7"
// implementation("androidx.navigation:navigation-compose:$nav_version")
implementation(libs.androidx.navigation)
}

使用 NavController

package zone.yue.jvtc.android.demo

import android.annotation.SuppressLint
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.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import zone.yue.jvtc.myapplication.ui.theme.MyApplicationTheme

class MainActivity : ComponentActivity() {
@SuppressLint("RestrictedApi")
@OptIn(ExperimentalMaterial3Api::class)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MyApplicationTheme(darkTheme = true) {
val navController = rememberNavController()

NavHost(
navController = navController,
startDestination = "/",
) {
composable("/") {
Scaffold(topBar = { TopAppBar({ Text("Root") }) }) {
Column(
Modifier.padding(it).fillMaxSize(),
Arrangement.Center,
Alignment.CenterHorizontally,
) {
Button({
navController.navigate("/AAA")
}) { Text("To AAA") }
Button({
navController.navigate("/BBB")
}) { Text("To BBB") }
}
}
}
composable("/AAA") {
Scaffold(topBar = { TopAppBar({ Text("AAA") }) }) {
Column(
Modifier.padding(it).fillMaxSize(),
Arrangement.Center,
Alignment.CenterHorizontally,
) {
Button({ navController.popBackStack() }) { Text("Back Root") }
}
}
}
composable("/BBB") {
Scaffold(topBar = { TopAppBar({ Text("BBB") }) }) {
Column(
Modifier.padding(it).fillMaxSize(),
Arrangement.Center,
Alignment.CenterHorizontally,
) {
Button({ navController.popBackStack() }) { Text("Back Root") }
}
}
}
}
}
}
}
}