从assets文件夹加载SVG的xml代码

时间:2017-03-30 15:56:48

标签: android xml svg android-drawable android-assets

我有很多SVG图像,目前转换为XML代码,存储在drawable/目录中。我使用以下代码检索它们并随机显示其中一个:

Field[] ID_Fields = R.drawable.class.getFields();
int[] resArray = new int[ID_Fields.length];
for (int i = 0; i < ID_Fields.length; i++)
{
  try
  {
    resArray[i] = ID_Fields[i].getInt(null);
  }
  catch (IllegalAccessException e)
  {
    e.printStackTrace();
  }
}

Random r = new Random();
int i1 = r.nextInt(ID_Fields.length - 1);
Log.i("TAG", "Selected index: " + i1);

Drawable drawable = ContextCompat.getDrawable(context, resArray[i1]);
imageView.setImageDrawable(drawable);

这很好 - 即使加载了所有可绘制的内容,也必须实现分离我的自定义图像的机制 - 并且所选图像正确显示在imageView中。

我想更改我的结构并将我的XML放入assets/flags/文件夹。但是,当我使用以下代码时,返回的drawable始终为null

AssetManager am = getApplicationContext().getAssets();
String[] files = new String[0];
try
{
  files = am.list("flags");
}
catch (IOException e)
{
  e.printStackTrace();
}
ArrayList<Drawable> drawables = new ArrayList<>();
for (String file : files)
{
  Drawable d = null;

  try
  {
    d = Drawable.createFromStream(am.open("flags/" + file), null);
  }
  catch (IOException e)
  {
    Log.i("EX2", "Second exception: " + file + " not found");
    e.printStackTrace();
  }

  drawables.add(d);
  if (d == null)
    Log.i("FLAG", "Null drawable");
}


Random r = new Random();
int i1 = r.nextInt(drawables.size() - 1);
Log.i("TAG", "Selected index: " + i1);

Drawable drawable = drawables.get(i1);
imageView.setImageDrawable(drawable);

为什么会这样?

0 个答案:

没有答案