如何在使用@Parcelize时对数据类中除构造函数之外的成员变量进行分割

2023-11-23

我正在使用 Room 和 Kotlin 数据类。例如,

@Entity(tableName = "Person")
@Parcelize
class Test(@ColumnInfo(name = "name") var name:String) : Parcelable{
    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "ID")
    var id: Long? = null
}

我可以使用构造函数创建实例并插入数据。我也收到警告"property would not be serialized into a 'parcel'"。当我尝试通过捆绑发送对象时,id 丢失了,正如警告所述,这是预期的。我怎样才能添加该成员ID在包裹里?我没有将 ID 保留在构造函数中,因为我希望它们自动生成。


您可以通过以下方式找到此信息文档:

@Parcelize要求在主构造函数中声明所有序列化属性。 Android 扩展将对类主体中声明的支持字段的每个属性发出警告。还,@Parcelize如果某些主要构造函数参数不是属性,则无法应用。

如果您的类需要更高级的序列化逻辑,您可以将其编写在伴随类中:

@Parcelize
data class User(val firstName: String, val lastName: String, val age: Int) : Parcelable {
    private companion object : Parceler<User> {
        override fun User.write(parcel: Parcel, flags: Int) {
            // Custom write implementation
        }

        override fun create(parcel: Parcel): User {
            // Custom read implementation
        }
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在使用@Parcelize时对数据类中除构造函数之外的成员变量进行分割 的相关文章

随机推荐