加载资源,变量? [英] Load resources with variables?

查看:161
本文介绍了加载资源,变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我加载XML文件资源,

I am loading XML file resource like this,

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

现在的情况是,这取决于各种因素可能有很多的XML文件以供选择。我怎么做?
在这种情况下,文件名是在实际上类似,与文件中的所有开始仅包含不同数目的端部
文件1,文件2,文件3等,这样我就可以形成与文件名的字符串变量,并添加后缀按规定形成像文件1的文件名(文件+ 1)。
问题是我不断收到各种错误以任何方式我尝试的文件名变量传递给方法(NullPointerEx,RESOURCEID未找到等)。
什么是解决这个问题的正确方法是什么?

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?

推荐答案

您可以使用<一个href=\"http://developer.android.com/reference/android/content/res/Resources.html#getIdentifier%28java.lang.String,%20java.lang.String,%20java.lang.String%29\">getIdentifier()但该文档提到:

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.

所以最好使用它引用的xml文件的数组。你可以声明它作为一个整数数组资源。例如,在 RES /价值/ arrays.xml

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>

然后在Java的:

And then in Java:

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

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

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

这篇关于加载资源,变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆