我有一个导航图,如下所示:
@Composable
fun NavGraph (
navController: NavHostController
) {
NavHost(
navController = navController,
startDestination = "Products"
) {
composable(
route = "Products"
) {
ProductsScreen(
navController = navController
)
}
composable(
route = "Product Details",
arguments = listOf(
navArgument("product") {
type = NavType.SerializableType(Product::class.java)
}
)
) {
val product = navController.previousBackStackEntry?.arguments?.getSerializable("product") as Product
ProductDetailsScreen(
navController = navController,
product = product
)
}
}
}
Run Code Online (Sandbox Code Playgroud)
在 ProductDetailsScreen 内,我希望单击产品以进一步导航到传递 Product 对象的详细信息屏幕:
LazyColumn {
items(
items = products
) { product ->
ProductCard( …Run Code Online (Sandbox Code Playgroud) android kotlin android-jetpack-compose jetpack-compose-navigation
我有一个用 jetpack compose 制作的应用程序,它工作得很好,直到我将 compose 导航库从版本2.4.0-alpha07升级到版本2.4.0-alpha08
在 alpha08 版本中,在我看来,该类arguments的属性NavBackStackEntry是 a val,所以它不能像我们在 2.4.0-alpha07 版本中那样重新分配。在2.4.0-alpha08版本中如何解决这个问题?
我的导航组件是这样的:
@Composable
private fun NavigationComponent(navController: NavHostController) {
NavHost(navController = navController, startDestination = "home") {
composable("home") { HomeScreen(navController) }
composable("details") {
val planet = navController
.previousBackStackEntry
?.arguments
?.getParcelable<Planet>("planet")
planet?.let {
DetailsScreen(it, navController)
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试使导航发生在详细信息页面的部分是在这个函数中:
private fun navigateToPlanet(navController: NavHostController, planet: Planet) {
navController.currentBackStackEntry?.arguments = Bundle().apply {
putParcelable("planet", planet)
}
navController.navigate("details")
}
Run Code Online (Sandbox Code Playgroud)
我已经尝试过简单地应用到函数arguments的重复navigateToPlanet使用 …
我想BluetoothDevice使用组合导航将 Parcelable 对象 ( ) 传递给可组合对象。
传递原始类型很容易:
composable(
"profile/{userId}",
arguments = listOf(navArgument("userId") { type = NavType.StringType })
) {...}
Run Code Online (Sandbox Code Playgroud)
navController.navigate("profile/user1234")
Run Code Online (Sandbox Code Playgroud)
但是我不能在路由中传递一个parcelable 对象,除非我可以将它序列化为一个字符串。
composable(
"deviceDetails/{device}",
arguments = listOf(navArgument("device") { type = NavType.ParcelableType(BluetoothDevice::class.java) })
) {...}
Run Code Online (Sandbox Code Playgroud)
val device: BluetoothDevice = ...
navController.navigate("deviceDetails/$device")
Run Code Online (Sandbox Code Playgroud)
上面的代码显然不起作用,因为它只是隐式调用toString().
有没有办法要么序列化Parcelable的String,所以我可以通过它的路线或通过导航参数作为比其他函数的对象navigate(route: String)?
android kotlin android-jetpack-navigation android-jetpack-compose