如何使用Parcelable绘制对象来传递如何使用、对象、Parcelable

2023-09-06 09:11:55 作者:孤家寡人

我有一类在那里我有一个绘制对象作为成员。 这个类我使用的各种活动发送的数据为 Parcelable 额外的费用。

I have a class where i have an Drawable as an member. This class i am using for sending data across activities as an Parcelable extra.

有关,我已经扩展了parceble,并实现所需的功能。

For that i have extended the parceble, and implemented the required functions.

我能够发送使用读/写INT /串的基本数据类型。 但我现在面临的问题,同时封送处理的可绘制对象。

I am able to send the basic data types using read/write int/string. But i am facing problem while marshaling the Drawable object.

有关,我试图给绘制对象转换为字节数组,但我正在逐渐类转换例外。

For that i tried to convert the Drawable to byte array, but i am getting class cast Exceptions.

我使用下面的code隐蔽我可绘制到Byte数组:

I am using following code to covert my Drawable to Byte array:

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);

和转换字节数组我用下面的code到绘制对象:

And to convert byte array to Drawable i am using following code:

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

当我运行此我得到类转换异常。

When i run this i get Class cast exception.

我们如何可以写/使用HashMap中通过绘制对象? 有没有什么办法,使我们可以通过绘制对象的包裹。

How can we write/pass Drawable using the HashMap? Is there any way by which we can pass Drawable in Parcel.

感谢。

推荐答案

正如你已经转换可绘制在code为位图,为什么不使用位图作为Parcelable类的成员。

As you already convert Drawable to Bitmap in your code, why not use Bitmap as an member of your Parcelable class.

位图实现Parcelable通过dafault的API,通过使用位图,你不需要做什么特别的事情在你的code,它会被包裹自动处理。

Bitmap implements Parcelable by dafault in API, by using Bitmap, you don't need to do anything special in your code and it will automatically handled by Parcel.

或者,如果你坚持使用可绘制,实现您的Parcelable因为是这样的:

Or if you insist to use Drawable, implement your Parcelable as something like this:

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);
  ... ...
}

希望这有助于。

Hope this helps.