我想在使用 @Parcelize
时忽略一个字段Kotlin 中的注释,以便该字段不被打包,因为该字段没有实现 Parcelable
界面。
从这里开始,我们得到一个错误,因为 PagedList
不可打包:
@Parcelize
data class LeaderboardState(
val progressShown: Boolean = true,
val pagedList: PagedList<QUser>? = null
) : Parcelable
给出:
Type is not directly supported by 'Parcelize'. Annotate the parameter type with '@RawValue' if you want it to be serialized using 'writeValue()'
标记为
@Transient
给出与上述相同的错误:@Parcelize
data class LeaderboardState(
val progressShown: Boolean = true,
//Same error
@Transient
val pagedList: PagedList<QUser>? = null
) : Parcelable
我发现了一个未记录的注释,名为
@IgnoredOnParcel
这给出了相同的错误,以及注释上的 lint 错误:@Parcelize
data class LeaderboardState(
val progressShown: Boolean = true,
//Same error plus lint error on annotation
@IgnoredOnParcel
val pagedList: PagedList<QUser>? = null
) : Parcelable
这种情况下的 lint 错误是:
@IgnoredOnParcel' is inapplicable to properties declared in the primary constructor
@Parcelize 真的没有办法做到这一点吗?
最佳答案
使用常规类并将属性移出主构造函数:
@Parcelize
class LeaderboardState(
val progressShown: Boolean = true,
pagedList: PagedList<QUser>? = null
) : Parcelable {
@IgnoredOnParcel
val pagedList: PagedList<QUser>? = pagedList
}
这显然是唯一的解决方案。确保在需要时覆盖 equals、hashCode、toString、copy 等,因为它们不会为常规类定义。
编辑:这是另一种解决方案,因此您不会丢失数据类的功能,也不会丢失自动分 block 。我在这里使用一个通用示例。
data class Person(
val info: PersonInfo
val items: PagedList<Item>? = null)
@Parcelize
data class PersonInfo(
val firstName: String,
val lastName: String,
val age: Int
) : Parcelable
您只保存
Person.info
并从中重新创建它。
关于android - 在 Kotlin 中使用 @Parcelize 注释时如何忽略字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61758963/