DrawableCompat.unwrap is not working pre Lollipop

866 views Asked by At

I'm using DrawableCompat.wrap to set tint on drawables in pre Lollipop and it's working fine. DrawableCompat.unwrap is not working pre Lollipop. I can't get the original drawable before the tint.

For example:

 if (v.isSelected()){
                Drawable normalDrawable = getResources().getDrawable(R.drawable.sample);
                Drawable wrapDrawable = DrawableCompat.wrap(normalDrawable);
                DrawableCompat.setTint(wrapDrawable, getResources().getColor(R.color.sample_color));
                imageButton.setImageDrawable(wrapDrawable);
 }else{
                Drawable normalDrawable = imageButton.getDrawable();
                Drawable unwrapDrawable = DrawableCompat.unwrap(normalDrawable);
                imageButton.setImageDrawable(unwrapDrawable);
 }

In pre lollipop devices DrawableCompact.unwrap returns the drawable with the tint and not the original one

1

There are 1 answers

0
eldivino87 On

If you want to clear the tint, call DrawableCompat.setTintList(drawable, null).

Unwrap isn't a destructive function, it's only there for you to get access to the original Drawable.

The following is an example code:

Drawable drawable = (Drawable) ContextCompat.getDrawable(getContext(), R.drawable.google_image);
if (condition) {
    drawable = DrawableCompat.wrap(drawable);
    DrawableCompat.setTint(drawable, ContextCompat.getColor(getContext(), R.color.grey700));
    DrawableCompat.setTintMode(drawable, PorterDuff.Mode.SCREEN);
    mImageView.setImageDrawable(drawable);
} else {
    drawable = DrawableCompat.unwrap(drawable);
    DrawableCompat.setTintList(drawable, null);
    mLoginStatusGoogleImageView.setImageDrawable(drawable);
}

In your case the code should be:

if (v.isSelected()) {
    Drawable normalDrawable = getResources().getDrawable(R.drawable.sample);
    Drawable wrapDrawable = DrawableCompat.wrap(normalDrawable);
    DrawableCompat.setTint(wrapDrawable, ContextCompat.getColor(getContext(), R.color.sample_color));
    DrawableCompat.setTint(wrapDrawable, getResources().getColor(R.color.sample_color));
    imageButton.setImageDrawable(wrapDrawable);
} else {
    Drawable normalDrawable = imageButton.getDrawable();
    Drawable unwrapDrawable = DrawableCompat.unwrap(normalDrawable);
    DrawableCompat.setTintList(unwrapDrawable, null);
    imageButton.setImageDrawable(unwrapDrawable);
}