Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change color of vector drawable path on button click

With the new android support update, vector drawables get backward compatibility. I have a vector image with various paths. I want the color of the paths to change on click of a button or programmatically based on an input value. Is it possible to access the name parameter of the vector path? And then change the color.

like image 225
suku Avatar asked Feb 25 '16 10:02

suku


People also ask

How to change color of vector drawable in android?

In the xml-file you can set custom color with the attribute android:fillColor but to change the color of vector drawable in runtime/dynamically. Tere is need to Change fillColor of a vector drawable in android programmatically, you can edit fill Color of a vector-file in Android programmatically using DrawableCompat.


1 Answers

The color of the whole vector can be changed using setTint.

You have to set up your ImageView in your layout file as this:

<ImageView     android:id="@+id/myImageView"     android:layout_width="wrap_content"     android:layout_height="wrap_content"     android:tint="@color/my_nice_color"     android:src="@drawable/ic_my_drawable"     android:scaleType="fitCenter" /> 

Then to change the color of your image:

DrawableCompat.setTint(myImageView.getDrawable(), ContextCompat.getColor(context, R.color.another_nice_color)); 

Note: myImageView.getDrawable() gives nullpointerexception if the vector drawable is set to the imageView as background.

like image 138
Marco Hernaiz Avatar answered Sep 20 '22 19:09

Marco Hernaiz