PhilLab PhilLab - 3 months ago 34
Android Question

Android Support Library: getDrawable independent if vector or not

When working with Android >= 5.0,

Drawable d = getResources().getDrawable(R.drawable.icon)


Correctly parses the XML and returns a valid drawable. But when using the new Vector Drawable Support Library (Version 23.4, Gradle 2.1.2), this code crashes under Android 4.


android.content.res.Resources$NotFoundException

...

Caused by: org.xmlpull.v1.XmlPullParserException: Binary XML file line #2: invalid drawable tag vector


The solution would be to use

Drawable d = VectorDrawableCompat.create(getResources(), R.drawable.icon, null);


But this crashes if the resource is not a vector resource:


java.io.FileNotFoundException: Corrupt XML binary file


So what code has to be used instead of the first line so that it works with Android 4 and Android 6 and with vector and non-vector drawables - e.g. in all circumstances this line was used in an Android 5.0+ project? The support library article does not mention a way to perform this migration

Answer

I found the solution.

You need to add the support VectorDrawable in your activity manually.

try this in your activity:

static {
    AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
}

You should check this blog entry for more information.

Comments