12

到目前为止,我一直在Parcelable毫无问题地处理对象,主要是因为它们的所有成员都是具有writeX()与之关联的方法的类型。例如,我这样做:

public String name;

private Foo(final Parcel in) {
    name = in.readString(); }
public void writeToParcel(final Parcel dest, final int flags) {
    dest.writeString(name); }

但是现在,如果我有Bar会员,事情对我来说有点冒险:

public Bar bar;

private Foo(final Parcel in) {
    bar = new Bar(); //or i could actually write some constructor for Bar, this is a demo.
    bar.memberString = in.readString();
}

public void writeToParcel(final Parcel dest, final int flags) {
    // What do I do here?
}

我是以错误的方式接近这个吗?我的writeToParcelto parcel member应该怎么做Bar

4

2 回答 2

30

正确且更面向对象的方法是让 Bar 也实现 Parcelable。

在您的私有 Foo 构造函数中读取 Bar :

private Foo(final Parcel in) {
  ... ...
  bar = in.readParcelable(getClass().getClassLoader());
  ... ...
}

要在 writeToParcel 方法中写入 Bar:

public void writeToParcel(final Parcel dest, final int flags) {
  ... ...
  dest.writeParcelable(bar, flags);
  ... ...
}

希望这可以帮助。

于 2012-03-28T21:24:13.753 回答
0

Parceables 是一种痛苦,只能通过价值传递而不是参考。我永远不会推荐使用它们。如果您的应用程序创建一个静态模型实例,并且只需获取对您需要的对象的 shim 引用。

于 2012-03-28T22:21:44.907 回答