Search code examples
javaandroidandroid-support-libraryandroid-vectordrawableandroid-support-design

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


Solution

  • You can use the following method to get drawable of Vector Drawable in pre 5.0.

    Drawable drawable = AppCompatResources.getDrawable(mContext, mImageTitleResId);