Use*_*337 15 android parcelable
我有一个班级,我有Drawable一个成员.
我用这个类作为Parcelable额外的活动跨活动发送数据.
为此,我扩展了parceble,并实现了所需的功能.
我能够使用读/写int/string发送基本数据类型.
但是在编组Drawable对象时我遇到了问题.
为此我试图转换Drawable为byte 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);
Run Code Online (Sandbox Code Playgroud)
并将字节数组转换为Drawable我使用以下代码:
final int contentBytesLen = in.readInt();
byte[] contentBytes = new byte[contentBytesLen];
in.readByteArray(contentBytes);
mMyDrawable = new BitmapDrawable(BitmapFactory.decodeByteArray(contentBytes, 0, contentBytes.length));
Run Code Online (Sandbox Code Playgroud)
当我运行这个时,我得到了类强制转换异常.
我们如何使用HashMap编写/传递Drawable?
我们有什么方法可以通过Parcel传递Drawable.
谢谢.
yor*_*rkw 29
由于您已在代码中将Drawable转换为位图,为什么不将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);
... ...
}
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助.
| 归档时间: |
|
| 查看次数: |
12490 次 |
| 最近记录: |