开发者

Load resources with variables?

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 th开发者_如何学运维e 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?


You could use getIdentifier() but the docs mention:

use of this function is discouraged. It is much more efficient to retrieve resources by identifier than by name.

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:

<?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>

And then in Java:

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

Of course, you'll need to update the array whenever you add a new xml file.


You can use the getIdentifier method of Resources to find the id.

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


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:

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

This would allow you retrieve the resource with a simple index operation.

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

Alternatively, if you needed a more descriptive mapping you can use any one of java's Map-based classes.

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);
    }
}

With this you would then get(String) the value by its name.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜