Search code examples
androidandroid-imageviewandroid-vectordrawable

Load a vector drawable into imageview from sd card


I want to show a vector image (say vectorimage.xml) in an imageview from the sd card. Please throw some insight on how to do this in android. What I have tried already :-

String imagePath = Environment.getExternalStorageDirectory() + "/ folder/productImage.xml";

bitmapImage = BitmapFactory.decodeFile(imagePath);
Drawable bgrImageDrawable = new BitmapDrawable(bitmapImage);

The above code snippet does not work since the bitmapImage is coming as null.


Solution

  • The BitmapFactory can't load vector drawables. You have to use the VectorDrawable or VectorDrawableCompat class. To load a vector drawable you need to use a xml loader.

    Some parser like the one for the resources need a precompiled binary xml file. You can find them in the apk file when you put the vector drawable in the drawable resource directory.

    Here is a sample to load it from the assets, you should be able to use a similar code for the loading from the sd card.

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

    This way needs at least Android 5.0