I would like to know what is the right way to handle internationalization for statements with runtime data added to it. For example 1) Your input "xyz" is excellent! 2) You were "4 years" old when you switched from "Barney and Freinds" to "Spongebob" shows.
The double quoted values are user data obtained or calculated at run time. My platforms are primarily Java/Android. A right solution for Western languages are preferred over weaker universal one.
To retrieve localized text (messages), use the java.util.ResourceBundle
API. To format messages, use java.text.MessageFormat
API.
Basically, first create a properties file like so:
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);
Then to get the messages by key, do:
String key1 = bundle.getString("key1");
String key2 = bundle.getString("key2");
Then to format it, do:
String formattedKey1 = MessageFormat.format(key1, "xyz");
String formattedKey2 = MessageFormat.format(key2, "4 years", "Barney and Friends", "Spongebob");
With regards to Android, the process is easier. You just have to put all those String
messages in the res/values/strings.xml
file. Then, you can create a version of that file in different languages, and place the file in a values
folder that contains the language code. For instance, if you want to add Spanish support, you just have to create a folder called res/values-es/
and put the Spanish version of your strings.xml
there. Android will automatically decide which file to use depending on the configuration of the handset.
One non-technical consideration. Embedding free data inside English phrases isn't going to look very smooth in many cultures (including Western ones), where you need grammatical agreement on e.g. number, gender or case. A more telegraphic style usually helps (e.g. Excellent input: "xyz") -- then at least everybody gets the same level of clunkiness!
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