17

我有一堂课,我有Drawable一个会员。
我使用这个类作为Parcelable额外的跨活动发送数据。

为此,我扩展了 parceble,并实现了所需的功能。

我能够使用读/写 int/string 发送基本数据类型。
但是我在编组 Drawable 对象时遇到了问题。

为此,我尝试将其转换Drawablebyte array,但我得到了类强制转换异常。

我正在使用以下代码将我的 Drawable 转换为 Byte 数组:

Bitmap bitmap = (Bitmap)((BitmapDrawable) mMyDrawable).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[]byteArray = stream.toByteArray();
out.writeInt(byteArray.length);
out.writeByteArray(byteArray);

并将字节数组转换为 Drawable 我使用以下代码:

final int contentBytesLen = in.readInt();
byte[] contentBytes = new byte[contentBytesLen];
in.readByteArray(contentBytes);
mMyDrawable = new BitmapDrawable(BitmapFactory.decodeByteArray(contentBytes, 0, contentBytes.length));

当我运行它时,我得到 Class cast 异常。

我们如何使用 HashMap 编写/传递 Drawable?
有什么方法可以在 Parcel 中传递 Drawable。

谢谢。

4

2 回答 2

31

由于您已经在代码中将 Drawable 转换为 Bitmap,为什么不使用 Bitmap 作为 Parcelable 类的成员。

Bitmap在 API 中默认实现 Parcelable,通过使用 Bitmap,您不需要在代码中做任何特殊的事情,它会由 Parcel 自动处理。

或者,如果您坚持使用 Drawable,请将 Parcelable 实现为如下所示:

public void writeToParcel(Parcel out, int flags) {
  ... ...
  // Convert Drawable to Bitmap first:
  Bitmap bitmap = (Bitmap)((BitmapDrawable) mMyDrawable).getBitmap();
  // Serialize bitmap as Parcelable:
  out.writeParcelable(bitmap, flags);
  ... ...
}

private Guide(Parcel in) {
  ... ...
  // Deserialize Parcelable and cast to Bitmap first:
  Bitmap bitmap = (Bitmap)in.readParcelable(getClass().getClassLoader());
  // Convert Bitmap to Drawable:
  mMyDrawable = new BitmapDrawable(bitmap);
  ... ...
}

希望这可以帮助。

于 2012-04-09T09:37:47.903 回答
1

在我的应用程序中,我将 Drawable/BitMap 保存到缓存中,并改为使用文件的路径字符串传递它。

不是您正在寻找的解决方案,但至少可以解决您的问题。

于 2012-04-09T09:00:30.123 回答