如何在Jetpack导航中传递可序列化对象的列表



我有一个名为Post:的类

data class Post(
val id: Long,
val type: PostType,
val latitude: Double,
val longitude: Double,
val address: String,
) : Serializable

我想使用Jetpack导航将这些对象的列表从一个片段传递到另一个片段,所以我尝试在导航图中添加一个参数,如下所示:

<fragment
android:id="@+id/destination_posts"
android:name="com.myapp.android.ui.main.posts.PostsFragment"
tools:layout="@layout/fragment_posts">
<argument
android:name="postsArg"
app:argType="com.myapp.android.core.entity.Post[]" />
</fragment>

我试着在第一个片段中这样做:

val action = PostsFragmentDirections.actionOpenPostsDetails(posts.toTypedArray())
navController.navigate(action)

并试图在第二个片段中接收它:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
arguments.let {
val postsFromArgs = PostsFragmentArgs.fromBundle(it).postsArg
}
}

但它抛出了一个例外:

Type mismatch: inferred type is Array<Post> but Array<(out) Parcelable!>? was expected

我不明白为什么它不起作用,因为正如我在文档中看到的,应该支持这种类型(https://developer.android.com/guide/navigation/navigation-pass-data#supported_argument_types(

因此,我通过将对象列表封装到另一个可串行化的数据类中来实现它,该数据类如下所示:

data class Posts(
val posts: List<Post>
) : Serializable

并以这种方式导航到另一个片段:

val action = PostsFragmentDirections.actionOpenPostsCluster(Posts(posts))
navController.navigate(action)

导航文档说,将复杂的数据结构传递给自变量被认为是一种反模式(你可以在上面Phil Dukhov的评论中找到它(,因此我认为我不推荐它

最新更新