red*_*lue 0 android android-resources
我正在加载这样的XML文件资源,
getResources().getXml(R.xml.fiel1);
Run Code Online (Sandbox Code Playgroud)
现在,情况是,根据因素,可能有许多xml文件可供选择.我怎么做?在这种情况下,文件名类似于以文件开头的所有内容都以不同的数字结尾,如file1,file2,file3等.所以我可以用文件名形成一个String变量,并根据需要添加一个后缀来形成像file1(文件+ 1)这样的文件名.问题是我不断尝试将文件名变量传递给方法时遇到各种错误(NullPointerEx,ResourceId Not found等).完成此任务的正确方法是什么?
您可以使用getIdentifier(),但文档提到:
不鼓励使用此功能.通过标识符而不是按名称检索资源要高效得多.
因此最好使用引用xml文件的数组.您可以将其声明为整数数组资源.例如,在res/values/arrays.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<integer-array name="xml_files">
<item>@xml/file1</item>
<item>@xml/file2</item>
etc...
</integer-array>
</resources>
Run Code Online (Sandbox Code Playgroud)
然后在Java中:
private XmlResourceParser getXmlByIndex(int index) {
Resources res = getResources();
return res.getXml(res.getIntArray(R.array.xml_files)[index - 1]);
}
Run Code Online (Sandbox Code Playgroud)
当然,每当添加新的xml文件时,您都需要更新数组.
| 归档时间: |
|
| 查看次数: |
1850 次 |
| 最近记录: |