简体   繁体   中英

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="http://schemas.android.com/apk/res/android" android:shape="oval">
  <stroke android:width="2dp" android:color="#c9c6af" />
  <solid android:color="#ffffffff" />
</shape>

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;
        try
        {
            istr = assetManager.Open(filePath);
            drawable = Drawable.CreateFromStream(istr, null);
        }
        catch (IOException e)
        {
            // handle exception
        }

        return drawable;
    }

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

https://developer.android.com/reference/android/view/LayoutInflater.html

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM