Android 使用变量来表示资源名称来访问 R.string 的内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3538649/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Accessing contents of R.string using a variable to represent the resource name
提问by MyName
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.
我有几个字符串需要翻译和显示。这些字符串在变量中。我在 strings.xml 文件中有翻译。
I want to display the "translated version" of the string. For example, inside an Activity:
我想显示字符串的“翻译版本”。例如,在 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>
If I used something like this:
如果我使用这样的东西:
nameDisplay.setText(R.string.KnownName);
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.
它会工作。但就我而言,名称存储在一个变量中,所以我不知道该怎么做才能使 setText 方法正常运行。
My current workaround is
我目前的解决方法是
String translation = ""
if(name == "Water") {
translation = getString(R.string.Water);
}
else {
...
}
nameDisplay.setText(translation);
... but this does not scale very well.
...但这不能很好地扩展。
Any suggestions?
有什么建议?
Should I store the translated version in the variable?
我应该将翻译后的版本存储在变量中吗?
回答by Konstantin Burov
You can use the method to convert string into int identifier:
您可以使用该方法将字符串转换为 int 标识符:
public static int getStringIdentifier(Context context, String name) {
return context.getResources().getIdentifier(name, "string", context.getPackageName());
}
Pass in an activity as context parameter (or any other Context instance). Then you can use the identifier as usual with getString() method.
将活动作为上下文参数(或任何其他上下文实例)传入。然后,您可以像往常一样通过 getString() 方法使用标识符。
Note that conversion from string to identifier uses reflection and thus can be not that fast, so use carefully.
请注意,从字符串到标识符的转换使用反射,因此速度不会那么快,因此请谨慎使用。
回答by ArK
private String getStringResourceByName(String aString)
{
String packageName = context.getPackageName();
int resId = getResources().getIdentifier(aString, "string", packageName);
return getString(resId);
}
回答by Suragch
Another thing you can do is map the string to the resource. That way you can have the string in a variable (or build it programmatically) and then use the map to look up the resource id.
您可以做的另一件事是将字符串映射到资源。这样您就可以将字符串放在变量中(或以编程方式构建它),然后使用映射查找资源 ID。
Example
例子
strings.xml
字符串.xml
<string name="water_english">water</string>
<string name="water_spanish">agua</string>
<string name="water_chinese">ˮ</string>
<string name="water_mongolian">???</string>
Code
代码
public class MainActivity extends AppCompatActivity {
private Map<String, Integer> stringForResourceIdMap = createMap();
private Map<String, Integer> createMap() {
Map<String, Integer> result = new HashMap<>();
result.put("water_english", R.string.water_english);
result.put("water_spanish", R.string.water_spanish);
result.put("water_chinese", R.string.water_chinese);
result.put("water_mongolian", R.string.water_mongolian);
return result;
}
private String getMyStringResource(String lookupString) {
int resourceId = stringForResourceIdMap.get(lookupString); // R.string.xxx
return getString(resourceId);
}
// ...
}
Note
笔记
If you are localizing your appwith different translations, then you should be using different resource folders.
如果您使用不同的翻译本地化您的应用程序,那么您应该使用不同的资源文件夹。
回答by Carsten Hagemann
As a Kotlin extension, ArK's answer could be written the following way. It also catches an exception when you give it an unknown key.
作为 Kotlin 的扩展,ArK 的答案可以写成以下方式。当您给它一个未知密钥时,它也会捕获异常。
fun Context.getStringWithResKey(nameResKey: String): String {
val resId = resources.getIdentifier(nameResKey, "string", packageName)
return try {
getString(resId)
} catch (e: Exception) {
Log.e(this.javaClass.simpleName, "Couldn't find string value for key '$nameResKey'", e)
""
}
}