在Android中使用动态R字符串

use*_*353 4 java string reflection resources android

我在使用存储在我的字符串时遇到问题strings.xml,我在那里存储了大量字符串.它们对我非常有用,因为我用它们来翻译我的程序.但是,现在我想动态地在这些字符串之间进行选择,我不知道该怎么做.用一个例子来理解它会更容易.我们假设我有以下字符串:

<string name="red">Red</string>
<string name="blue">Blue</string>
<string name="green">Green</string>
<string name="yellow">Yellow</string>
Run Code Online (Sandbox Code Playgroud)

现在让我们假设我有一个函数,例如,它传递了一个带颜色的字符串"yellow".现在我只有一个解决方案,做一个非常大的开关(非常非常巨大,因为我有很多字符串),我认为必须有一个选项将我的函数输出转换为正确的参数.我的意思是,如果我有一个函数返回我"yellow",并且我想使用它R.strings.yellow,它们之间必须有一个链接.我不知道你是否可以使用任何反射来实现这一目标.

你能帮助我吗?

Mar*_*res 12

有一种方法比普通的android方法"getIdentifier"快10倍,不仅使用字符串而且还可以使用反射以非常简单的方式获取R文件中存在的drawable或任何其他资源,如下所示:

try {
        //Get the ID
        Field resourceField = R.string.class.getDeclaredField("yourResourceName");
        //Here we are getting the String id in R file...But you can change to R.drawable or any other resource you want...
       int resourceId = resourceField.getInt(resourceField);

       //Here you can use it as usual
       String yourString = context.getString(resourceId);

    } catch (Exception e) {
        e.printStackTrace();
    } 
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.

问候!


Log*_*kup 8

使用两步过程查找要加载的ID.首次使用Resources.getIdentifier(),例如:

int id = getResources().getIdentifier("yellow", "string", getPackageName());
Run Code Online (Sandbox Code Playgroud)

然后,在检查id不为零(表示找不到资源)后,使用id获取正常的字符串:

String colour = getString(id);
Run Code Online (Sandbox Code Playgroud)