NavType
是用来描述参数类型和值的类,它用于在不同目的地之间传递参数。在Jetpack Compose Navigation中,我们可以使用NavType
来指定导航目的地之间传递的参数类型,包括基本类型(如Int
和Boolean
)、自定义类型(如data class
)、Parcelable
和Enum
等。
以下是一个示例,在两个目的地之间传递一个参数:
定义NavType
类型:
sealed class AppNavType {
object Counter : NavType() {
override fun get(bundle: Bundle, key: String): Int {
return bundle.getInt(key)
}
override fun parseValue(value: String): Int {
return value.toInt()
}
override fun put(bundle: Bundle, key: String, value: Int) {
bundle.putInt(key, value)
}
}
}
定义两个目的地:
val navController = rememberNavController()
navController.graph = navController.createGraph(startDestination = "screen1") {
destination("screen1") {
action(route = "screen2/{count}") { backStackEntry ->
val count =
backStackEntry.arguments?.getInt("count") ?: throw IllegalArgumentException("Count is missing")
if (count < 0) {
throw IllegalArgumentException("Count can't be negative")
}
NavGraphBuilder(navController = navController).composeRoute("screen2/$count")
}
}
destination("screen2/{count}") {
val count = navArgument("count") {
type = AppNavType.Counter
}
arg(type = AppNavType.Counter) {
defaultValue = 0
nullable = false
}
action(route = "") {
NavGraphBuilder(navController = navController).popBackStack()
}
}
}
在screen1
中跳转到screen2
时传递参数:
Button(onClick = {
navController.navigate("screen2/$count", navOptions {})
}) {
Text(text = "Navigate with parameter")
}
在`screen
上一篇:AndroidJetpackComposeNavigation和使用companionObject作为参数传递数据类的解决方法
下一篇:AndroidJetpackComposePreviewUI_MODE_NIGHT_YES在预览中无法显示暗色背景。