【问题标题】:Dynamic Resource Loading Android动态资源加载 Android
【发布时间】:2010-09-06 04:05:03
【问题描述】:

我正在尝试找到一种方法来打开仅在运行时确定名称的资源。

更具体地说,我希望有一个 XML 引用应用程序 apk 中的一堆其他 XML 文件。为了便于解释,假设主要的 XML 是 main.xml,其他 XML 是 file1.xmlfile2.xmlfileX.xml。我想要的是读取main.xml,例如提取我想要的XML的名称(fileX.xml),然后读取fileX.xml。我面临的问题是我从main.xml 中提取的内容是一个字符串,我找不到将其更改为R.raw.nameOfTheFile 的方法。

有人有想法吗?

我不想:

  • 将所有内容重新组合到一个巨大的 XML 文件中
  • 在一个巨大的 switch case 中硬编码 main.xml,将数字/字符串链接到资源 ID

【问题讨论】:

  • 我遇到了类似的问题,但我没有得到任何可接受的答案。有人可以为这个问题开始赏金吗?

标签: android


【解决方案1】:

我没有将它用于原始文件或 xml 布局文件,但对于可绘制对象,我使用它:

getResources().getIdentifier("fileX", "drawable","com.yourapppackage.www");

获取资源的标识符(R.id)。您需要将 drawable 替换为其他内容,可能是 rawlayout(未经测试)。

【讨论】:

  • 感谢您的出色回答。对于那些在相同情况下的人here is a good explanation on the subject(一旦我有了函数的名称就很简单了):getResources().getIdentifier("fileX", "raw", application package);
  • 死链接? @JasonRogers 啊,nvm - 应该是 anddev.org/…
  • no not dead link casperOne 删除了我的帖子并将其更改为评论,但没有花时间正确完成(又名链接断开)这里是链接:anddev.org/tinytut_-get_resources_by_name__getidentifier-t460.html
【解决方案2】:

我写了这个方便的小助手方法来封装它:

public static String getResourceString(String name, Context context) {
    int nameResourceID = context.getResources().getIdentifier(name, "string", context.getApplicationInfo().packageName);
    if (nameResourceID == 0) {
        throw new IllegalArgumentException("No resource string found with name " + name);
    } else {
        return context.getString(nameResourceID);
    }
}

【讨论】:

  • 非常有用,谢谢,但我们从来都不需要字符串。有时流会更好。
【解决方案3】:

还有一种方法:

int drawableId = R.drawable.class.getField("file1").getInt(null);

根据this blog,它比使用 getIdentifier 快 5 倍。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多