Translate an application

Share this idea :

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.

values directory

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.

Example:

  • 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.

Example:

  • values-en-rUS : English for the United State,
  • values-fr-rFR : for the French of France,
  • values-fr-rCA : for French Canada.

For more information: https://developer.android.com/guide/topics/resources/providing-resources.html#AlternativeResources

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.

strings.xml in english

In the file explorer, create a directory called values-fr. Copy/paste the strings.xml file located in values.

one directory per language

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).

My app in English

Change your system language and choose French. We restart the application from Android Studio.

My app in french

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

*