运行时的Android翻译

时间:2015-01-22 12:07:00

标签: android translation

Android中有没有办法在运行时使用自己的翻译文件翻译字符串?

e.g。 英文文件:

hello world : Hello world.

德文档:

hello world: Hallo Welt.

就像在Webframeworks(Symfony,Rails,...)中一样

1 个答案:

答案 0 :(得分:2)

我可以想到两种方法。一种是指定Android语言/区域代码,并使用不同的res / values / strings.xml来转换字符串值。但这会影响整个应用程序。以下是supporting different languages

的参考资料

另一种方法是为服务器响应转换创建这样的本地化资源文件。

所以strings.xml就是这样的:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="error_msg_ge">Fehlermeldung</string>
    <string name="error_msg_en">Error Message</string>
</resources>

以下只是一个伪代码,因为你没有发布任何代码。

if(!isSuccess) {
  TextView textView = new TextView(this);
  textView.setText(R.string.error_msg_ge)
}

如果我们真的想要更精确,那么我们可以在资源文件中指定更多错误消息,并根据服务器返回的错误消息交换使用。

所以XML可能就像这样

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="error_ge_timeout">auszeit</string>
    <string name="error_ge_noresult">kein Ergebnis</string>
    <string name="error_en_timeout">timeout</string>
    <string name="error_en_noresult">no result</string>
</resources>

然后

if(!isSuccess) {
  TextView textView = new TextView(this);
  if(errMsg.equals(R.string.error_en_timeout)) {
     textView.setText(R.string.error_ge_timeout);
  } //...and so on

}

最后但并非最不重要,您还可以使用第三方API进行翻译。但是,由于您正在翻译从服务器收到的错误消息,我不确定是否有必要,因为它不是一个会话目的所以它可能是一个矫枉过正。无论如何,有很多方法可以实现它。