Right way of using vector drawables in Android Studio

In this tutorial I will guide you on How to import Vector Assets and Drawables in your Android application.

I will also cover how to give support for devices which do not support vector assets using AppCompat library.

Importing Vector Asset using Android Studio

In case of Vector Assets You do not directly copy paste your icons and images in drawable folder.

There is tool in Android Studio for importing Vector Assest or Scalable Vector Graphics (SVG).

Go to File => New => and select Vector Asset.

android studio import vector graphics
Importing Vector Assets (SVG) Android Studio

You can also enable RTL (Right to Left) support. When your application will be running in RTL mode, your SVG icon will be flipped automatically.

After this step SVG file which you imported above will be converted into XML file.

Vector Drawable XML Preview Android Studio
Vector Drawable XML Preview

At this step we are ready to use above icon in our application but there is a lot more to do.

Backward Compatibility for SVG

Vector Drawables or Scalable Vector Graphics (SVG) were introduced in Android 5.0 (API Level 21).

If your application support devices lower than API Level 21 still you can use Vector Drawables on devices lower than API Level 21 using AppCompat Library.

Because AppCompat Library suport Android 2.1  (API Level 7+).

//For Gradle Plugin 2.0+
 android {
   defaultConfig {
     vectorDrawables.useSupportLibrary = true
    }
 }

Using this property, your vector drawables will be converted into PNG files on devices lower than API Level 21.

Rules for using Vector Drawables in Android Apps

  • You cannot use Vector Drawables on any other views except ImageView on pre Lollipop devices.
  • You cannot use drawableLeft and DrawableRight property on pre Lollipop devices for TextView and EditText.

Add this code in your Application Class.

open class ApplicationClass : Application() {

    init {
        AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
    }
}

Using Vector Drawable for ImageView

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:srcCompat="@drawable/ic_back" />

We cannot use android:src property on Vector Drawables instead we use app:srcCompat property.

Copyright:  http://developine.com/

Contact Us