Nigel DH Nigel DH -4 years ago 111
Android Question

Creating a Drawable from xml file in Assets folder

I have a sub-folder inside the assets folder which contains some xml layouts (just simple shapes.) My goal is to be able to create a Drawable object to use as the background of a view. Currently it's just simple shapes, but there will eventually be a lot of them. I don't want to use the resources area for several reasons (no sub-folders, don't want to have to hard code resource paths, and others.)

Normal code which works on image drawables returns null with xml files. Does anyone have any pointers as to how to do this? Code examples below.

xml File:

<shape xmlns:android="" android:shape="oval">
<stroke android:width="2dp" android:color="#c9c6af" />
<solid android:color="#ffffffff" />

c# code for reading the file, very similar to java. Yes I know I need to close the InputStream:

public static Drawable GetDrawableFromAsset(Context context, string filePath)
AssetManager assetManager = context.Assets;

Stream istr;
Drawable drawable = null;
istr = assetManager.Open(filePath);
drawable = Drawable.CreateFromStream(istr, null);
catch (IOException e)
// handle exception

return drawable;

Answer Source

It turns out you can't do this for performance reasons:

For performance reasons, view inflation relies heavily on pre-processing of XML files that is done at build time. Therefore, it is not currently possible to use LayoutInflater with an XmlPullParser over a plain XML file at runtime; it only works with an XmlPullParser returned from a compiled resource (R.something file.)

This relates to using the XmlPullParser which is what I had to end up trying anyway (the create from stream doesn't work for the same reasons.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download