Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Tint using DrawableCompat

I'm trying to tint an image prior to Android API level 21. I've successfully tinted items using:

<android:tint="@color/red"/> 

However, I can't seem to figure out how to do this through code on an ImageView:

Drawable iconDrawable = this.mContext.getResources().getDrawable(R.drawable.somedrawable); DrawableCompat.setTint(iconDrawable, this.mContext.getResources().getColor(R.color.red)); imageView.setImageDrawable(iconDrawable); 

I've tried setting the TintMode but this seems to make no different. Am I using the v4 compatibility class DrawableCompat incorrectly?

like image 384
Hippopatimus Avatar asked Nov 06 '14 19:11

Hippopatimus


People also ask

What is drawable tint android?

Android Drawables Tint a drawableA drawable can be tinted a certain color. This is useful for supporting different themes within your application, and reducing the number of drawable resource files.

How do I change the color of a drawable in XML?

Use app:drawableTint="@color/yourColor" in the xml instade android:drawableTint="@color/yourColor" . It has the backward compatibility.


1 Answers

In case anyone needs to use DrawableCompat's tinting without affecting other drawables, here's how you do it with mutate():

Drawable drawable = getResources().getDrawable(R.drawable.some_drawable); Drawable wrappedDrawable = DrawableCompat.wrap(drawable); wrappedDrawable = wrappedDrawable.mutate(); DrawableCompat.setTint(wrappedDrawable, getResources().getColor(R.color.white)); 

Which can be simplified to:

Drawable drawable = getResources().getDrawable(R.drawable.some_drawable); drawable = DrawableCompat.wrap(drawable); DrawableCompat.setTint(drawable.mutate(), getResources().getColor(R.color.white)); 
like image 127
Renan Ferrari Avatar answered Sep 30 '22 11:09

Renan Ferrari