我想知道处理添加了运行时数据的语句的国际化的正确方法是什么。例如 1) 您输入的“xyz”非常好! 2) 当您从“Barney and Freinds”转到“Spongebob”节目时,您只有“4 岁”。
双引号中的值是在运行时获取或计算的用户数据。我的平台主要是 Java/Android。西方语言的正确解决方案优于较弱的通用解决方案。
最佳答案
Java
要检索本地化文本(消息),请使用 java.util.ResourceBundle
应用程序接口(interface)。要格式化消息,请使用 java.text.MessageFormat
API。
基本上,首先创建一个 properties file像这样:
key1 = Your input {0} is excellent! key2 = You were {0} old when you switched from {1} to {2} shows.
The {n}
things are placeholders for arguments as you can pass in by MessageFormat#format()
.
Then load it like so:
ResourceBundle bundle = ResourceBundle.getBundle("filename", Locale.ENGLISH);
然后要通过 key 获取消息,请执行以下操作:
String key1 = bundle.getString("key1");
String key2 = bundle.getString("key2");
然后格式化它,做:
String formattedKey1 = MessageFormat.format(key1, "xyz");
String formattedKey2 = MessageFormat.format(key2, "4 years", "Barney and Friends", "Spongebob");
另见:
安卓
对于 Android,这个过程更容易。您只需将所有这些 String
消息放入 res/values/strings.xml
文件中。然后,您可以创建该文件的不同语言版本,并将该文件放在包含语言代码的 values
文件夹中。例如,如果你想添加西类牙语支持,你只需要创建一个名为 res/values-es/
的文件夹并将你的西类牙语版本的 strings.xml
放在那里. Android 将根据手机的配置自动决定使用哪个文件。
另见:
关于java - 你如何处理 "Your input ' xyz 的国际化'非常棒!”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3300728/