android - 使用 Parcebale 在片段之间通过 Bundle 发送自定义类对象
问题描述
我在我的主要活动中使用片段,我想将我的自定义类“ TaskWithUserAndProfile
”的对象发送到TaskDetailsFragment
我发现你可以Bundle
用它来发送一个字符串,但是当我尝试用Parcebale
. 以下是我的代码的一些部分,以便更好地理解:
TaskWithUserAndProfile.kt
class TaskWithUserAndProfile() : Parcelable{
override fun writeToParcel(p0: Parcel?, p1: Int) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
var profile = Profile()
var task = Task()
var user = User()
constructor(parcel: Parcel) : this() {
//profile = parcel.read
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<TaskWithUserAndProfile> {
override fun createFromParcel(parcel: Parcel): TaskWithUserAndProfile {
return TaskWithUserAndProfile(parcel)
}
override fun newArray(size: Int): Array<TaskWithUserAndProfile?> {
return arrayOfNulls(size)
}
}
}
HomeFragment.kt
//Inside onCreateView
adapter = TasksAdapter(tasksArray) { item ->
println(item.profile)
val bundle = Bundle()
bundle.putParcelable("MyItem", item)
val taskDetailsFragment = TaskDetailsFragment()
taskDetailsFragment.arguments = bundle
val fragmentTransaction = fragmentManager.beginTransaction()
fragmentTransaction.replace(R.id.container, taskDetailsFragment)
fragmentTransaction.addToBackStack(null)
fragmentTransaction.commit()
}
我的实现 Parcebale 的类应该是什么样子,然后我如何发送和接收片段中的项目对象?
解决方案
如果您想继续使用 parcelize,请尝试以下示例:
@Parcelize
data class TaskWithUserAndProfile(var profile:Profile, var task :Task, var user:User) : Parcelable{}
我可能会从你的课程中遗漏一些东西,但这个想法应该是这样的,所以使用注释 @Parcelize 和 Parcelable 实现(不需要覆盖任何方法)。
Update
谢谢提醒。您必须将其添加到您的 gradle 文件中:
androidExtensions {
experimental = true
}
推荐阅读
- c# - 如何使用公共交通检测到 rabbit mq 的连接问题?
- asp.net-core - IdentityServer4 中的 AddSigningCredential - 自签名或来自证书颁发机构
- javascript - 修复 RN StyleSheet 中的位置
- java - 使用 CURL 和 SSL 获取请求
- c - scanf没有在循环C中多次运行
- angular - 如何使用其父集合访问嵌套的 Firebase 集合
- c# - C# 以 30 FPS 录制屏幕 - Win Forms
- node.js - 使用 Node.js 和 PM2 同时处理多个连接
- java - PreparedStatement 参数索引超出范围
- typo3 - TYPO3 VHS 仅获取图像标签