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
You can use the following method to get drawable of Vector Drawable in pre 5.0.
Drawable drawable = AppCompatResources.getDrawable(mContext, mImageTitleResId);
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.
another possible solution what I found so far
ResourcesCompat.getDrawable(context.resources, resId, theme)
and context should be your activity (but not application context)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With