17

私はDrawableメンバーとしているクラスを持っています。
このクラスは、アクティビティ間でデータを追加で送信するために使用していますParcelable

そのために、パーセブルを拡張し、必要な機能を実装しました。

読み取り/書き込みの 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);

そして、バイト配列を Drawable に変換するために、次のコードを使用しています:

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

これを実行すると、クラスキャスト例外が発生します。

HashMap を使用して Drawable を作成/渡すにはどうすればよいですか?
Drawable in Parcel を渡す方法はありますか。

ありがとう。

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 に答える