正如我在NavType文档中看到的那样,有一个名为NavType.SerializableType的子类型:
用于 Serializable NavArguments。
SerializableType 的类构造函数接受一个类型的参数,该参数Class<D?>?
应该是:
是 Serializable 的子类型的类。
现在,我有以下课程:
data class Product (
var key: String? = null,
//Other 15 different fields.
): Serializable
以下是 NavHost 的外观:
NavHost(
navController = navController,
startDestination = "Products"
) {
composable(
route = "Products"
) {
ProductsScreen(
navController = navController
)
}
composable(
route = "Product/{product}",
arguments = listOf(
navArgument("product") {
type = NavType.SerializableType(Product::class.java)
}
)
) {
val product = navController.previousBackStackEntry?.arguments?.getSerializable("product") as Product
ProductScreen(
navController = navController,
product = product
)
}
我使用以下内容从起始目的地(产品屏幕)导航到(产品屏幕):
navController.currentBackStackEntry?.arguments?.putSerializable("product", product)
navController.navigate("Product/${product}")
我因这个错误而崩溃:
可序列化不支持默认值。
但是,如果我通过删除更改上述内容/{product}
:
NavHost(
navController = navController,
startDestination = "Products"
) {
composable(
route = "Products"
) {
ProductsScreen(
navController = navController
)
}
composable(
route = "Product",
arguments = listOf(
navArgument("product") {
type = NavType.SerializableType(Product::class.java)
}
)
) {
val product = navController.previousBackStackEntry?.arguments?.getSerializable("product") as Product
ProductScreen(
navController = navController,
product = product
)
}
并按照此处的说明进行导航:
navController.currentBackStackEntry?.arguments?.putSerializable("product", product)
navController.navigate("Product")
我得到:
java.lang.IllegalArgumentException:与请求匹配的导航目的地 NavDeepLinkRequest{ uri=android-app://androidx.navigation/Product } 在导航图中找不到 NavGraph(0x0) startDestination={Destination(0xb543811) route=Products}
如何将 Product 类型的 Serializable 对象添加到 NavArguments 并正确返回?我不想将对象转换为 JSON 字符串。这甚至可能吗?