Home » Android » android – How to get vectors drawables with gradients to work in < API 24?

android – How to get vectors drawables with gradients to work in < API 24?

Posted by: admin May 14, 2020 Leave a comment

Questions:

I am writing an app where it uses vector drawable with gradient tags extensively.

What are the steps I need to take so that devices with different API levels could work with these icons without us manually converting the SVG files into PNG files of different sizes?

Below is a typical vector icon we use after I import it into android studio

<vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt"
        android:width="72dp"
        android:height="103dp"
        android:viewportWidth="72.0"
        android:viewportHeight="103.0">
    <path
        android:pathData="M63,40.3L63,26.87C63,12.03 50.91,0 36,0 21.09,0 9,12.03 9,26.87v13.43c-4.97,0 -9,4.01 -9,8.96v44.78C0,98.99 4.03,103 9,103h54c4.97,0 9,-4.01 9,-8.96L72,49.26c0,-4.95 -4.03,-8.96 -9,-8.96zM18,26.87c0,-9.9 8.06,-17.91 18,-17.91 9.94,0 18,8.02 18,17.91v13.43L18,40.3L18,26.87zM63,94.04L9,94.04L9,49.26h54v44.78zM31.5,74.89v5.72c0,2.47 2.02,4.48 4.5,4.48 2.48,0 4.5,-2.01 4.5,-4.48v-5.72c2.68,-1.55 4.5,-4.41 4.5,-7.71 0,-4.95 -4.03,-8.96 -9,-8.96s-9,4.01 -9,8.96c0,3.31 1.82,6.16 4.5,7.71z"
        android:fillType="nonZero">
        <aapt:attr name="android:fillColor">
<gradient 

        android:startY="0.0"
        android:startX="0.0"
        android:endY="103.0"
        android:type="linear"
        android:endX="72.0">
<item android:offset="0.0" android:color="#FFFA8561" />
<item android:offset="1.0" android:color="#FFFC5D5D" />
            </gradient></aapt:attr></path>
</vector>

I notice that attributes like “startX, startY” is API > 24 only. I am willing to sacrifice the precision of these coordinates/directions so long as a gradient can be seen.

Is it possible for me to change these attributes a little bit so that at least a gradient can be shown across all device API levels?

Thanks

How to&Answers:

Try to use this support library in gradle for using vector drawable in lower versions. for reference https://developer.android.com/guide/topics/graphics/vector-drawable-resources.html

For Gradle Plugin 2.0+

   android {
    defaultConfig {
      vectorDrawables.useSupportLibrary = true
                  }
            }

For Gradle Plugin 1.5 or below

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