How to change color of vector drawable path on but

2020-01-28 02:52发布

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.

8条回答
Animai°情兽
2楼-- · 2020-01-28 03:15

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.

查看更多
【Aperson】
3楼-- · 2020-01-28 03:16

Check my answer on this other question: https://stackoverflow.com/a/38418049/1335438.

It is a great idea on how to manage this by using Themes and parameterizing the paths in order to be able to set them dynamically.

查看更多
登录 后发表回答