Android-Working with Vector Drawable (Part 2)

In our previous tutorial , we have discussed  what is a Vector, what is VectorDrawable , difference between svg and Vector and different ways to convert svg images to vectorDrawable.This tutorial will be mainly focused on how to support VectorDrawable on preLollipop android devices.

Introduction :
Previously , vectors were not supported on pre-lollipop android devices, but using support lib 23.2.0 and above, we can easily use on devices running Android 2.1 and above.Two new vector classes were introduced with this support lib :

  1. VectorDrawableCompat
  2. AnimatedVectorDrawableCompat ( Can be used only for API 11 and above )

How to use ?

a ) Enabling vectorDrawable  flag on build.gradle :
First, check your Gradle plugin version on Android Studio :
(Go to File -> Project Structure -> Project )

if you are using Gradle plugin v2.0 or above, make the following changes to build.gradle file :

    defaultConfig { 
        vectorDrawables.useSupportLibrary = true 

else ,

android {
    defaultConfig {
    // Stops the Gradle plugin's automatic rasterization of vectors
        generatedDensities = [] 
    // Flag to tell aapt to keep the attribute ids around
    aaptOptions {
        additionalParameters "--no-version-vectors" 

Using Vectors on App ?

One thing you should keep in mind that VectorDrawableCompat is only used for API 20 and below. For API 21 and above devices, default VectorDrawable class will be used.

So , how to use vector images ?
Simple..just use app:srcCompat attribute inside ImageView.

app:srcCompat="@drawable/legoman" />

Note : we can use app:srcCompat for nonvector images also.

b) During runtime :

ImageView iv = (ImageView) findViewById(...);

That’s it. following screenshots are one on Android device 2.3 and right one is on Android 5.

 vector_2.3 vector_5

This project is shared on Github. Clone it from here.


Leave a Reply