android - 在 Kotlin 中使用 @Parcelize 注释时如何忽略字段

标签 android kotlin parcelable

我想在使用 @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/

相关文章:

java - 需要工作解决方案以在自定义应用程序中使用 Android 模式锁定屏幕(而不是源代码重定向)

android - OpenCV Android Studio 设置问题

android - 无法在 Intent : The Method Put Extra is Ambiguous for the type Intent 中传递自定义对象

java - Parcelable 类中的 Parcelable 列表未使用 Parcel.readTypedList 回读

android - 多个 fragment 同时访问同一个数据库

android - 如何为android自定义文件类型分配一个图标?

android - Rx Java - 只有创建 View 层次结构的原始线程

android - 根据List改变constraintlayout

java - libgdx 地面不起作用

android-studio - Kotlin - 可解析类型不匹配 : Required: String, 找到 : String?