2012-04-09 4 views
13

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

私はそれをparcebleを拡張し、必要な機能を実装しました。

私はread/write int/stringを使用して基本データ型を送信できます。
しかし、Drawableオブジェクトのマーシャリング中に問題が発生しています。

私はDrawablebyte arrayに変換しようとしましたが、クラスキャスト例外が発生しています。私は取得し、これを実行すると

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

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のためにバイト配列を変換するために:私はバイト配列に私のDrawableのをひそかに次のコードを使用しています

クラスキャスト例外。

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

ありがとうございました。

答えて

25

Drawableをコード内で既にBitmapに変換しているので、BitmapをParcelableクラスのメンバーとして使用しないでください。

は、APIでデフォルトでParcelableを実装しています。ビットマップを使用すると、コード内で特別な処理を行う必要はなく、自動的に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); 
    ... ... 
} 

は、この情報がお役に立てば幸いです。

+0

たとえば、ビットマップやその他のタイプのオブジェクトがある場合、イメージをパーセルに書き込む必要はありませんか?それは私のためにすべての見つけるとダンディーが動作しますか? – eddiecubed

+1

@yorkw 'getBitmap()'はデフォルトで 'Bitmap'を返します、なぜあなたは再度型キャストするのですか? – blizzard

+2

'BitmapDrawable'は廃止されました。 – AdamMc331

1

私のアプリでは、Drawable/BitMapをキャッシュに保存し、代わりにファイルのパス文字列を使用して渡しました。

あなたが探していた解決策ではありませんが、少なくともあなたの問題の代替案です。

+1

次に、キャッシュからドロワブルを保存/削除する必要があります。上記のコードに間違いがありますか? – User7723337

関連する問題