Question

I'm facing problem in adding a drawable object to a Parcel object, in order to send an object from one activity to another activity.

There are methods like writeString(String) to add strings to a Parcel object. But do not know how to add a Drawable to the Parcel object.

Was it helpful?

Solution

You cannot add a Drawable to a Parcel, as Drawable does not implement the Parcelable interface. Certain types of Drawable might implement Parcelable, but I am not aware of any.

You can put in the Parcel some identifier (e.g., drawable resource ID) and have the recipient obtain the Drawable on its own.

OTHER TIPS

I think you can try wrapping the Drawable inside an object that implements Parcelable.

You can do that using Bitmap and BitmapDrawable.

Let's say you have a Drawable called drawable and a Parcel (in which the object should be written) called parcel.

To write a Drawable into a Parceable:

if ( drawable != null ) {
    Bitmap bitmap = (Bitmap) ((BitmapDrawable) drawable).getBitmap();
    parcel.writeParcelable(bitmap, flags);
}
else {
    parcel.writeParcelable(null, flags);
}

To read the Drawable from the Parceable:

Bitmap bitmap = (Bitmap) in.readParcelable(getClass().getClassLoader());
if ( bitmap != null ) {
    drawable = new BitmapDrawable(bitmap);
}
else {
    drawable = null;
}

In particular, since the constructor BitmapDrawable (Bitmap bitmap) has been deprecated, you might want to use BitmapDrawable (Resources res, Bitmap bitmap) instead.

drawable = new BitmapDrawable(context.getResources(), bitmap);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top