2011-04-11 101 views
0

我加载像这样的XML文件资源,用变量加载资源?

getResources().getXml(R.xml.fiel1); 

现在,该方案是根据多种因素可能有很多的XML文件以供选择。我怎么做? 在这种情况下,文件名是相似的,所有以文件开始的文件只以 file1,file2,file3等不同的数字结尾,所以我可以用文件名形成一个字符串变量,并根据需要添加后缀以形成像file1(文件+ 1)的文件名。 问题是我不断收到各种错误(NullPointerEx,ResourceId未找到等),无论我尝试将文件名变量传递给方法。 完成此操作的正确方法是什么?

+0

您可能需要使用反射来获取基于名称的相应ID并传递该ID。 – 2011-04-11 19:04:17

回答

5

你可以使用getIdentifier()但文档提到:

使用此功能被劝阻。 通过标识符而不是名称检索 资源效率更高。

因此,最好使用引用xml文件的数组。您可以声明它为integer array resource。例如,在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> 

然后在Java中:

private XmlResourceParser getXmlByIndex(int index) { 
    Resources res = getResources(); 
    return res.getXml(res.getIntArray(R.array.xml_files)[index - 1]); 
} 

当然,你需要更新数组只要添加一个新的XML文件。

3

您可以使用Resources的getIdentifier方法来查找id。

Resources res = getResources(); 
for(/* loop */) { 
    int id = res.getIdentifier("file" + i, "xml", "my.package.name"); 
    res.getXml(id); 
} 
2

对于getIdentifier建议,如果资源数量在编译时是固定的,则建议的替代方法是在标识符和资源之间创建静态映射。

因此,例如,你可以使用后缀数字ID:

class Whatever { 
    static final int[] resources = new int[] { 
     R.xml.file1, R.xml.file2, R.xml.file3 
    } 
} 

这将允许您检索与一个简单的索引操作的资源。

getResources().getXml(resources[i]); 

另外,如果你需要一个更具描述性的映射你可以使用Java的Map基类中的任何一个。

class Whatever { 
    static final Map<String, Integer> resources = new HashMap<String, Integer>(); 

    static { 
     resources.put("file1", R.xml.file1); 
     resources.put("file2", R.xml.file2); 
     resources.put("file3", R.xml.file3); 
     resources.put("something_else", R.xml.something_else); 
    } 
} 

有了这个,你会然后get(String)价值其名称。