程式碼範例

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            AlbumAppTheme {
                Navigation()
            }
        }
    }
}

@Composable
fun Navigation() {
    var navController = rememberNavController()
    NavHost(navController = navController, startDestination = "first") {
        composable(route = "first") {
            FirstScreen(navController)
        }
        composable(
            route = "second",
        ) {
            SecondScreen(navController)
        }
        composable(
            route = "third/{name}",
            arguments = listOf(
                navArgument("name") {
                    type = NavType.StringType
                    defaultValue = "Kirin"
                    nullable = true
                }
            )
        ) { entry->
            ThirdScreen(name = entry.arguments?.getString("name"))
        }
    }
}

@Composable
fun FirstScreen(navController: NavController) {
    Column {
        Text(
            text = "First Screen"
        )
        Button(
            onClick = {
                navController.navigate("second")
            }
        ) {
            Text("Go to Second Screen")
        }
    }
}

@Composable
fun SecondScreen(navController: NavController) {
    Column {
        Text(
            text = "Second Screen"
        )
        Button(
            onClick = {
                navController.navigate("third/{john}")
            }
        ) {
            Text("Go to Third Screen")
        }
    }
}

@Composable
fun ThirdScreen(name: String?) {
    Column{
        Text(
            text = "Hello, $name"
        )
        Button(
            onClick = {
		navController.navigate("first") {
                    popUpTo("first") {
                        inclusive = true
                    }
                }
            }
        ) {
            Text("Back to First Screen")
        }
    }
}

參考資料

Android Dev: Navigating with Compose

Last modified: 2023 年 12 月 25 日

Author

Comments

Write a Reply or Comment

Your email address will not be published.