How to set VectorDrawable as an image for ImageView programmatically

Hamid.Waezi picture Hamid.Waezi · Dec 12, 2016 · Viewed 62.3k times · Source

I want to set some vectorDrawables to a ImageView in Android Studio.

I can set png and jpg drawable easily but when i want to set VectorDrawable, it does not work on imageview.

img.setImageResource(R.drawable.ic_home);

ic_home is VectorDrawable and this code doesn't work.

Answer

Pramod Baggolli picture Pramod Baggolli · Apr 20, 2017

If you want to use vector drawables (less OR greater than API 21) just do the following:

Set the image programmatically (e.g. in your activity):

imageView.setImageResource(R.drawable.ic_left_arrow_blue); 

or by XML:

app:srcCompat="@drawable/your_vector_name"

In your app's build.gradle you need to include:

android {
    defaultConfig {
        vectorDrawables.useSupportLibrary = true
    }
}

And for vector support for less then API 21, add the following to onCreate:

AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);