简体   繁体   English

从Assets文件夹中的xml文件创建Drawable

[英]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. 我在Assets文件夹中有一个子文件夹,其中包含一些xml布局(只是简单的形状。)我的目标是能够创建一个Drawable对象用作视图的背景。 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. 适用于图像可绘制对象的普通代码对xml文件返回null。 Does anyone have any pointers as to how to do this? 是否有人对如何执行此操作有任何指示? Code examples below. 下面的代码示例。

xml File: xml文件:

<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. 用于读取文件的C#代码,与Java非常相似。 Yes I know I need to close the InputStream: 是的,我知道我需要关闭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 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. 出于性能原因,视图膨胀在很大程度上依赖于在构建时完成的XML文件的预处理。 Therefore, it is not currently possible to use LayoutInflater with an XmlPullParser over a plain XML file at runtime; 因此,当前无法在运行时对纯XML文件使用LayoutInflater和XmlPullParser。 it only works with an XmlPullParser returned from a compiled resource (R.something file.) 它仅适用于从编译资源(R.something文件)返回的XmlPullParser。

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.) 这与使用XmlPullParser ,这是我无论如何都要结束的尝试(出于相同的原因,从流创建无效)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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