使用一个变量来重新present资源名称访问R.string内容 [英] Accessing contents of R.string using a variable to represent the resource name

查看:109
本文介绍了使用一个变量来重新present资源名称访问R.string内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个字符串,我需要翻译和显示。这些字符串变量。我翻译了的strings.xml文件。

I have a few strings which I need to translate and display. Those strings are in variables. I have the translation in the strings.xml file.

我要显示的字符串译本。例如,一个活动里面的:

I want to display the "translated version" of the string. For example, inside an Activity:

String name = "Water";
TextView nameDisplay = new TextView(this).
nameDisplay.setText(name);

在字符串文件我也有定义

In the strings file I have the definition

<string name="Water">French word for Water</string>

如果我用的是这样的:

nameDisplay.setText(R.string.KnownName);

这是可行的。但是,在我的情况下,该名称存储在一个变量,所以我不知道该怎么做,才能为setText方法才能正常工作。

it would work. But in my case, the name is stored in a variable so I do not know what to do in order for the setText method to function properly.

我目前的解决方法是

String translation = ""

if(name == "Water") {
  translation = getString(R.string.Water);
}
else {
  ...
}

nameDisplay.setText(translation);

...但是,这并不规模非常好。

... but this does not scale very well.

有什么建议?

我应该存储在翻译版本中的变量?

Should I store the translated version in the variable?

感谢。

推荐答案

您可以使用的方法来转换字符串转换成int标识符:

You can use the method to convert string into int identifier:

public static int getStringIdentifier(Context context, String name) {
    return context.getResources().getIdentifier(name, "string", context.getPackageName());
}

传递中的活性作为上下文参数(或任何其他上下文实例)。然后你可以使用该标识符像往常一样用getString()方法。

Pass in an activity as context parameter (or any other Context instance). Then you can use the identifier as usual with getString() method.

请注意从字符串转换为标识使用反射,因而可没有那么快,所以请谨慎使用。

Note that conversion from string to identifier uses reflection and thus can be not that fast, so use carefully.

这篇关于使用一个变量来重新present资源名称访问R.string内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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