Search code examples
androidandroid-vectordrawable

VectorDrawable createFromStream does not seem to work


I am trying to load vector drawables from the assets.

It works fine when I use png files:

final String name = "image.png";
final InputStream stream = context.getAssets().open(name);
drawable = Drawable.createFromStream(stream, name);
stream.close();

I tried using VectorDrawable.createFromStream() and VectorDrawableCompat.createFromStream() but both always return null.

When I add the vector drawable to the drawbles resources it can be loaded without a problem.

I also tried using the binary xml file which gets created when adding the vector file to the drawables resources.

I use API level 24 and Support libs 24.2.0 with Android 5.1.1 to test this. It should work on Android 4.2 and later.

Does anyone know how to fix this?

This issue could relate to this one: Load a vector drawable into imageview from sd card


Solution

  • After looking at the Android source code I found a solution. The method createFromStream does not seem to support vector drawables. Because it uses a BitmapFactory.

    but we can load them as xml resource:

    final XmlResourceParser parser = context.getAssets().openXmlResourceParser("assets/folder/image.xml");
    drawable = VectorDrawableCompat.createFromXml(context.getResources(), parser);
    

    The image.xml musst be a precompiled binary xml file. You can extract them out of the generated apk file when you add the vector drawable to the drawable resources.

    The problem with this approach is, that it needs Android 5. But I need a working code for Android 4.2. Anyone an idea?