Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set VectorDrawable as an image for ImageView programmatically

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.

like image 861
Hamid.Waezi Avatar asked Dec 12 '16 09:12

Hamid.Waezi


People also ask

How do I change the color of an image in programmatically?

Tint color means when we want to change the color of the image while rendering in ImageView. In XML is very easy to change tint color by just setting up the attribute android:tint="" in the ImageView tag, as shown in the following example.


2 Answers

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);   
like image 148
Pramod Baggolli Avatar answered Sep 26 '22 08:09

Pramod Baggolli


For those who want to load a vector drawable programmatically for other uses, such as setting a drawableLeft or otherwise, you can use:

Drawable drawable = AppCompatResources.getDrawable(context, drawableRes); 

where the context is a AppCompatActivity.

like image 31
Jawnnypoo Avatar answered Sep 24 '22 08:09

Jawnnypoo