Is there a way in Android to translate strings with an own translation file at runtime?
e.g. english file:
hello world : Hello world.
german file:
hello world: Hallo Welt.
Like in Webframeworks (Symfony, Rails, ...)
I can think of two ways to do so. One is to specify the Android language/region code and use different res/values/strings.xml to translate the string values. But this will affect the entire app. Here is the reference on supporting different languages
Another way to do so is to create localized resource file like this for server response translation.
So the strings.xml would be like this:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="error_msg_ge">Fehlermeldung</string>
<string name="error_msg_en">Error Message</string>
</resources>
Below is just a pseudo code since you didn't post any code.
if(!isSuccess) {
TextView textView = new TextView(this);
textView.setText(R.string.error_msg_ge)
}
If we really want to be more precise, then we can specify more error messages in the resource file and swap to use based on the error message returned from the server.
So the XML could be like this
<?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>
Then
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
}
Lastly but not the least, you can also utilize third party API to do the translation. But since you are translating error message received from the server, I am not sure if that is necessary since it is not a conversational purpose so it could be an overkill. In any case, there are many ways to achieve it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With