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.
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):
or by XML:
In your app's
build.gradle
you need to include:And for vector support for less then API 21, add the following to
onCreate
:As per official android developer blog, no changes for setImageResource() method at runtime for vectorDrawables.
For more details, check out this nice article AppCompat — Age of the vectors by Google Developer.
Delete two folders form your drawable folder then rebuild your project it will work properly
for Java Code use:
and for XML use:
Use this:
instead of
ImageButton
,ImageView
etc.If vector type image is used. Mainly for custom views.
For those who want to load a vector drawable programmatically for other uses, such as setting a drawableLeft or otherwise, you can use:
where the context is a AppCompatActivity.