Android Support Library: getDrawable independent if vector or not
M

3

24

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

Mockheroic answered 7/6, 2016 at 16:53 Comment(1)
I assume they were expecting developers to know up front whether the resource is a vector drawable or not. That's reasonable for app developers, less so for library developers. Off the cuff, I'd try the VectorDrawableCompat, and fall back to getDrawable() if you get a FileNotFoundException.Ioves
I
50

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

Drawable drawable = AppCompatResources.getDrawable(mContext, mImageTitleResId);
Indomitable answered 14/10, 2016 at 8:26 Comment(3)
Available in support lib 24.2.x.Affect
Thanks a lot! Helped us fix a always reproducing crash in our app while using vector drawables on pre 5.0 devices.Terra
This should be the answer.Byrle
L
7

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.

Loganloganberry answered 8/6, 2016 at 21:44 Comment(1)
Thanks, that worked. FYI, it is ``setCompatVectorFromResourcesEnabled()`, the blog post has a typo.Mockheroic
Q
1

another possible solution what I found so far

ResourcesCompat.getDrawable(context.resources, resId, theme)

and context should be your activity (but not application context)

Quietism answered 28/4, 2017 at 10:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.