动态资源加载Android

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3648942/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 11:09:39  来源:igfitidea点击:

Dynamic Resource Loading Android

android

提问by Jason Rogers

I'm trying to find a way to open resources whose name is determined at runtime only.

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

More specifically, I want to have a XML that references a bunch of other XML files in the application apk. For the purpose of explaining, let's say the main XML is main.xmland the other XML are file1.xml, file2.xmland fileX.xml. What I want is to read main.xml, extract the name of the XML I want (fileX.xml), for example, and then read fileX.xml. The problem I face is that what I extract form main.xmlis a string and I can't find a way to change that to R.raw.nameOfTheFile.

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

Anybody has an idea?

有人有想法吗?

I don't want to:

我不想:

  • regroup everything in one huge XML file
  • hardcode main.xml in a huge switch case that links a number/string to the resource ID
  • 将所有内容重新组合到一个巨大的 XML 文件中
  • 在一个巨大的 switch case 中硬编码 main.xml,将数字/字符串链接到资源 ID

回答by Mathias Conradt

I haven't used it with raw files or xml layout files, but for drawables I use this:

我没有将它与原始文件或 xml 布局文件一起使用,但对于可绘制文件,我使用了这个:

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

to get the identifier (R.id) of the resource. You would need to replace drawable with something else, maybe rawor layout(untested).

获取资源的标识符 (R.id)。您可能需要用其他东西替换 drawable,也许rawlayout(未经测试)。

回答by E-Riz

I wrote this handy little helper method to encapsulate this:

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

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);
    }
}

回答by syonip

There is another method:

还有一种方法:

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

According to this blogit's 5x times faster than using getIdentifier.

根据此博客,它比使用 getIdentifier 快 5 倍。