Extending a class that implements Parcelable

后端 未结 3 1889
太阳男子
太阳男子 2021-01-11 09:54

I have a class, we\'ll call it class A, that implements Parcelable.

I have a second class, we\'ll call it class B, that extends class A.

My question is:

3条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-11 10:44

    How do I write class B's member variables to the Parcel and then write it's parent class's (ie: class A's) member variables to the Parcel

    Class B overrides writeToParcel() from Class A, chaining to the superclass and also adding its own objects to the Parcel.

    (and, subsequently, read them in)?

    Class B implements public static final Parcelable.Creator CREATOR in such a way that it can let both classes read their stuff in. If you take the approach of creating a constructor on Class B that takes a Parcel as a constructor parameter, just chain to the superclass constructor (to let Class A do its work), then read Class B's data.

    The key will be to do them both in the same order. If you intend to let Class A read its data first, Class A must write its data first.

    Is there some nifty trick to not needing to rewrite class A's Parcel code?

    Inheritance and chaining to the superclass.

提交回复
热议问题