使用变量加载资源?
我正在像这样加载 XML 文件资源,
getResources().getXml(R.xml.fiel1);
现在的情况是,根据因素,可能有许多 xml 文件可供选择。我该怎么做? 在这种情况下,文件名是相似的,因为所有文件都以文件开头,仅以不同的数字结尾,例如 file1,file2,file3等,所以我可以用文件名形成一个字符串变量,并根据要求添加后缀以形成像file1(文件+1)这样的文件名。 问题是,无论我尝试将文件名变量传递给方法,我都会不断收到各种错误(NullPointerEx、ResourceId Not find 等)。 实现这一目标的正确方法是什么?
I am loading XML file resource like this,
getResources().getXml(R.xml.fiel1);
Now, the scenario is that depending on factors there may be many xml files to choose from. How do I do that?
In this case the filename is similar in the fact that all starts with file only ends with different numbers like
file1, file2,file3 etc., So I can just form a String variable with the file name and add a suffix as per requirement to form a filename like file1 (file+1).
Problem is I keep getting various errors (NullPointerEx, ResourceId Not found etc) in whatever way I try to pass the filename variable to the method.
What is the correct way of accomplishing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 getIdentifier() 但文档提到:
因此最好使用引用 xml 文件的数组。您可以将其声明为整数数组资源。例如,在
res/values/arrays.xml
中:然后在 Java 中:
当然,每当添加新的 xml 文件时,您都需要更新数组。
You could use getIdentifier() but the docs mention:
So it's better to use an array which references the xml files. You can declare it as an integer array resource. Eg, in
res/values/arrays.xml
:And then in Java:
Of course, you'll need to update the array whenever you add a new xml file.
您可以使用 getIdentifier 资源的方法来查找 id。
You can use the getIdentifier method of Resources to find the id.
假设资源数量在编译时是固定的,
getIdentifier
建议的替代方案是在标识符和资源之间创建静态映射。例如,您可以使用后缀数字 ID:
这将允许您通过简单的索引操作检索资源。
或者,如果您需要更具描述性的映射,您可以使用 java 的任何一个
Map
基于类。有了这个,您就可以通过名称
get(String)
该值。An alternative to the
getIdentifier
suggestions, assuming the number of resources is fixed at compile time, would be to create a static mapping between an identifier and the resource.So for example you could use the suffixed numerical ID:
This would allow you retrieve the resource with a simple index operation.
Alternatively, if you needed a more descriptive mapping you can use any one of java's
Map
-based classes.With this you would then
get(String)
the value by its name.