Looking for to add different languages into your application or switching between languages dynamically?

Here is a tutorial to show how to answer to these questions trough an helper what I wrote in Java, and just need the locale code of the language what you want to use in your application.

First of all, you will be to add a value directory (in res/) related to every language what you want to add into your application.

 

The resources

In order to create a resource directory associated to a specified language, create a new Android resource directory, select “Language” and click on “>>” button.
You should arrive on this view.

Screen Shot 2015-04-08 at 12.47.09

Select a language and it will create automatically a directory under the format “values-fr” if you select the french one.

Here is the result after creating a directory for French and Finnish.

Screen Shot 2015-04-08 at 12.39.47

 

Add a string.xml file in every of the directory what you create with the translation into the language associated.
If you wish, you can also add a dimens.xml or a styles.xml in order to custom the style of your application.

Now that you have all the directories with all the files translated, here is the code to change the local of your device and load automatically and programmatically the translated files.

 

 

The code

Screen Shot 2015-04-08 at 12.36.12

 

You can use this method in that way:

LanguageHelper.changeLocale(this.getRessources(), “fr”);

Assuming that we are calling this method inside of an activity (to be able to use this) and get access to the resources of your project.
Giving “fr” in parameter will change the local of the device and load automatically the files into your values-fr directory.

Some locales are already defined in the Locale object, like English, French, Chinese, Italian and the locale can be initialised just in calling: Locale.an for example.

Screen Shot 2015-04-08 at 12.34.16

I invite you to read a little bit more about Locale on android dev documentation.

If the language what you want to use is not in the list, no panic you can create a new Locale object. It takes in parameter the country code (2 letters).

If you have any files into the assets directory, html or json files for example. Do not forget to load them as well.
Changing the locale does not load them automatically.

 

Find this example on Github here.

Leave a Reply

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

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>