【问题标题】:Android translation at runtime运行时的 Android 翻译
【发布时间】:2015-01-22 12:06:59
【问题描述】:

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

例如 英文文件:

hello world : Hello world.

德语文件:

hello world: Hallo Welt.

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

【问题讨论】:

  • 您是否正在尝试制作翻译应用程序?还是只是翻译资源字符串?
  • 我在服务器响应中收到英语错误消息,我想在运行时用我自己的翻译将它们翻译成不同的语言。
  • 那是谷歌翻译的,不是自己的

标签: android translation


【解决方案1】:

我可以想到两种方法。一种是指定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 进行翻译。但是由于您正在翻译从服务器收到的错误消息,我不确定这是否有必要,因为它不是会话目的,所以它可能是一个矫枉过正的问题。无论如何,有很多方法可以实现它。

【讨论】:

    猜你喜欢
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-19
    • 2022-01-05
    • 2017-02-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多