Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 891
PhilLab Avatar asked Jun 07 '16 16:06

PhilLab


3 Answers

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

Drawable drawable = AppCompatResources.getDrawable(mContext, mImageTitleResId);
like image 160
Thinker Luffy Avatar answered Oct 26 '22 21:10

Thinker Luffy


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.

like image 7
jmarkstar Avatar answered Oct 26 '22 22:10

jmarkstar


another possible solution what I found so far

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

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

like image 1
orium Avatar answered Oct 26 '22 23:10

orium