Internationalize an application (think about translations)
The translation of an application must be planned at the start of the project and BeansLegacy isn’t an exception.
Remember, we have seen that Android Studio created a directory res and subdirectory values visible in the Project Explorer.
The directory contains the values strings.xml file. This file must contain all the strings of your application. They must all be in this file, and nowhere else. Why so strict?
There are many benefits, and the first advantage is to greatly simplify the internationalization of your application (the translation in several languages).
The values directory is the default directory. In many case it contains the English language.
You can create new ones according to the languages that your application will support.
- values-en : for English (English is often placed in the default directory)
- values-fr : for French,
- values-es : for Spanish,
The language code (fr, en, es …) match the country code as defined in ISO 639-2.
It’s also possible to add a second code corresponding to the geographical area (preceded by “r”). This code is defined in the ISO 3166-1-alpha-2.
- values-en-rUS : English for the United State,
- values-fr-rFR : for the French of France,
- values-fr-rCA : for French Canada.
If Android can’t find the appropriate language of the device, it will take strings.xml default file, so the one in the values directory.
Go to practice
Let’s take our first Android application called Hello World.
Open strings.xml and modify app_name. I choose Localization.
In the file explorer, create a directory called values-fr. Copy/paste the strings.xml file located in values.
Open the new strings.xml file (directory values-en), and replace Hello World by Bonjour le monde (I also change app_name adding fr).
We launch the emulator and runs our application: it’s in English (the default language in the emulator).
Change your system language and choose French. We restart the application from Android Studio.
It’s in French ! 🙂
Note : If you set Toto instead of Hello World, your application will display Toto 😉
The source code of this simple project is available on the GitHub repository of Bean’s Legacy.
This post is also available in 2 - Lire cette page en français.