android - 使用导航参数传递数据时,如何解决错误 ArrayList cannot be cast to android.os.Parcelable[] in Kotlin?
问题描述
我正在尝试使用这样的导航参数将类别数据(ArrayList)从一个片段发送到另一个片段。
fun setUpArgumentForSearchDestination(categories: ArrayList<Category>) {
val searchDestination = fragmentView.findNavController().graph.findNode(R.id.destination_search)
searchDestination?.addArgument(
"allCategories", NavArgument.Builder()
.setType(NavType.ParcelableArrayType(Category::class.java))
.setDefaultValue(categories)
.build())
}
在搜索片段中,我从这样的参数接收数据:
arguments?.let {
// I get error in the code below:
val categories = it.getParcelableArrayList<Category>("allCategories")
}
我收到错误消息:
java.util.ArrayList 不能转换为 android.os.Parcelable[]
即使我不确定这个问题的原因,我也试图找到答案,看来我必须Category
像在这个线程中那样自定义我的类:Read & writing arrays of Parcelable objects
但我是初学者,并不太了解该线程的答案。我已经尝试实现parcelable
,但它仍然不起作用。这是我的Category
课
class Category() : Parcelable {
var id : Int = 0
var name : String = ""
var parentID : Int = 0
var imageURL : String = ""
constructor(parcel: Parcel) : this() {
id = parcel.readInt()
name = parcel.readString()
parentID = parcel.readInt()
imageURL = parcel.readString()
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.apply {
writeInt(id)
writeString(name)
writeInt(parentID)
writeString(imageURL)
}
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<Category> {
override fun createFromParcel(parcel: Parcel): Category {
return Category(parcel)
}
override fun newArray(size: Int): Array<Category?> {
return arrayOfNulls(size)
}
}
}
解决方案
AParcelableArrayType
只支持对象数组,Parcelable
不支持列表。因此,您必须ArrayList
使用以下方法将您的转换为数组toTypedArray()
:
val searchDestination = fragmentView.findNavController().graph.findNode(R.id.destination_search)
searchDestination?.addArgument(
"allCategories", NavArgument.Builder()
.setType(NavType.ParcelableArrayType(Category::class.java))
.setDefaultValue(categories.toTypedArray())
.build())
}
您将使用Safe Args或代码检索 Parcelables 数组,例如:
arguments?.let {
val categories = it.getParcelableArray("allCategories") as Array<Category>
}
导航不支持 Parcelables 的 ArrayLists。
推荐阅读
- python - 在不知道其公式的情况下,在python中提取并绘制曲线的一阶导数?
- reactjs - 如何在自动完成材质 UI 中呈现自定义 jsx 元素
- python - Django 静态视频无法在 Chrome 或 Edge 上播放
- android - Kotlin 1.5.20 打破了 dagger/moshi 的 kapt
- c++ - spidev ioctl 返回无效参数错误
- azure - 在 Azure DevOps 参数化中使用 assignable_scope 构建 azurerm_role_definition
- postgresql - postgres 选择 nextval 会导致一些性能问题吗?
- go - flag.Args()后如何访问
- django-models - 如何计算月份有可用位置的不同imei
- c - 将 void* 复制到数组中的某个位置,C