我正在尝试找到一种方法来打开名称仅在运行时确定的资源.
更具体地说,我希望有一个XML引用应用程序apk中的一堆其他XML文件.为了解释,让我们说主要的XML main.xml和其他XML是file1.xml,file2.xml和fileX.xml.我想要的是读取main.xml,提取我想要的XML的名称(fileX.xml例如),然后阅读fileX.xml.我面临的问题是我提取的形式main.xml是一个字符串,我找不到改变它的方法R.raw.nameOfTheFile.
有人有想法吗?
我不想:
Mat*_*adt 56
我没有使用它与原始文件或xml布局文件,但对于drawables我使用这个:
getResources().getIdentifier("fileX", "drawable","com.yourapppackage.www");
Run Code Online (Sandbox Code Playgroud)
获取资源的标识符(R.id).您需要将drawable替换为其他东西,可能raw或layout(未经测试).
E-R*_*Riz 24
我写了这个方便的小助手方法来封装它:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
还有另一种方法:
int drawableId = R.drawable.class.getField("file1").getInt(null);
Run Code Online (Sandbox Code Playgroud)
根据这篇博客,它比使用getIdentifier快5倍.
| 归档时间: |
|
| 查看次数: |
25873 次 |
| 最近记录: |