首页 > 解决方案 > 使用 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 的类应该是什么样子,然后我如何发送和接收片段中的项目对象?

标签: androidandroid-fragmentskotlin

解决方案


如果您想继续使用 parcelize,请尝试以下示例:

@Parcelize
data class TaskWithUserAndProfile(var profile:Profile, var task :Task, var user:User) : Parcelable{}

我可能会从你的课程中遗漏一些东西,但这个想法应该是这样的,所以使用注释 @Parcelize 和 Parcelable 实现(不需要覆盖任何方法)。

Update 谢谢提醒。您必须将其添加到您的 gradle 文件中:

androidExtensions {
    experimental = true
}

推荐阅读