[英]How to fetch resource in android from string
I have a json file which contains name of resource that I want to use in my code, but i do not know how? 我有一个json文件,其中包含我想在代码中使用的资源名称,但是我不知道怎么办? Json file
Json文件
{
file1: "file1.xml",
file2: "file2.xml"
...
}
I need to do somethin like this 我需要做这样的事情
InputStream f1 = this.getResources().openRawResource(R.raw.file1);
InputStream f2 = this.getResources().openRawResource(R.raw.file2);
InputStream f3 = this.getResources().openRawResource(R.raw.file3);
Than use this in my code further 比在我的代码中进一步使用它
Try with this: 试试这个:
String rawFileName = "file1.xml"
int resId = context.getResources().getIdentifier(rawFileName, "raw", context.getPackageName());
InputStream f1 = this.getResources().openRawResource(resId);`
Give the Resources#getIndentifier()
method a try, though you'll probably need to strip out the file extension: 尝试使用
Resources#getIndentifier()
方法,尽管您可能需要Resources#getIndentifier()
文件扩展名:
public static int getIdentifierForRawXmlFileName(Context context, String fileName) {
final Resources res = context.getResources();
final String packageName = context.getPackageName();
if (fileName.endsWith(".xml") {
fileName = fileName.subString(0, fileName.lastIndexOf(".xml"));
}
return res.getIdentifier(fileName, "raw", packageName);
}
Which you could use as: 您可以将其用作:
final int rawId = getIndetifierForRawXmlFileName(this, "file1.xml");
final InputStream is = getResources().openRawResource(rawId);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.