2

问题是:如何在实现接口的parcelables上有效地实现parceling。

我有这个案子。由两个具体类(见下图)和一个应该是 Parcelable 的容器(PictureProviders)实现的接口。

问题是:如何有效地打包图片列表?

  1. 我们不能使用 read/writeTypedList,因为我们不知道将哪个创建者传递给 readTypedList。
  2. 我们可以使用 read/writeParcelableArray,但这意味着将 List 复制到一个数组中。另外你会使用哪个类加载器?getClass().getClassLoader() 会好吗?
  3. 我们也可以使用读/写列表。你会使用哪个类加载器?getClass().getClassLoader() 会好吗?

示例代码:

public interface PictureProvider extends Parcelable {
  public Collection<Picture> getAvailablePictures(); 
}

public class SimplePictureProvider implements PictureProvider {

  // ...

  private List<Picture> pictures;

  public SimplePictureProvider(Parcel in) {
    // THIS IS WHERE THE QUESTION APPLIES
  }

  @Override
  public void writeToParcel(Parcel dest, int flags) {
    // THIS IS WHERE THE QUESTION APPLIES
  }

  public int describeContents() {
    return 0;
  }

  public static final Parcelable.Creator<SimplePictureProvider> CREATOR = new Parcelable.Creator<SimplePictureProvider>() {
    public SimplePictureProvider createFromParcel(Parcel in) {
      return new SimplePictureProvider(in);
    }

    public SimplePictureProvider[] newArray(int size) {
      return new SimplePictureProvider[size];
    }
  };
}

public interface Picture extends Parcelable {
  public byte[] getPictureData();
}

public class RemotePicture implements Picture {

  // ...

  private String pictureUrl;

  public RemotePicture(Parcel in) {
    pictureUrl = in.readString();
  }

  @Override
  public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(pictureUrl);
  }

  public int describeContents() {
    return 0;
  }

  public static final Parcelable.Creator<RemotePicture> CREATOR = new Parcelable.Creator<RemotePicture>() {
    public RemotePicture createFromParcel(Parcel in) {
      return new RemotePicture(in);
    }

    public RemotePicture[] newArray(int size) {
      return new RemotePicture[size];
    }
  };
}

public class LocalPicture implements Picture {

  // ...

  private String picturePath;

  public LocalPicture(Parcel in) {
    picturePath = in.readString();
  }

  @Override
  public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(picturePath);
  }

  public int describeContents() {
    return 0;
  }

  public static final Parcelable.Creator<LocalPicture> CREATOR = new Parcelable.Creator<LocalPicture>() {
    public LocalPicture createFromParcel(Parcel in) {
      return new LocalPicture(in);
    }

    public LocalPicture[] newArray(int size) {
      return new LocalPicture[size];
    }
  };
}
4

2 回答 2

0

writeParcelableArray如果您知道尺寸不会改变并且*List尺寸会动态变化,我会选择。作为类加载器传递null以使用基本/默认类加载器。

于 2013-06-10T16:39:52.487 回答
0

I used read/writeList with getClass().getClassLoader()? That seems to do the job.

于 2013-06-24T18:38:52.010 回答