Pages

Saturday, April 13, 2013

Supporting multiple languages

Hi there,

This post is kind of like a follow-up of my previous post on Supporting screen orientations. It's also an example of how to improve your app by using different resource files. If you create a new Android project with the Android SDK Tools, for example in Eclipse, there will be a res/ folder created in the top level of your project. You will also find res/values/strings.xml. This file contains UI strings of your project.

Values

The Android Developers team advises you to place all your UI strings in this file. One of the advantages of this is that you'll be able to add different languages to the project without having to make any changes in your code. The only thing you need to do is create a new values folder in the res/ directory. The name of this folder should be values followed by a hyphen and the two-lettered language code defined by ISO 639-1. For example: values-fr for French. Just copy the strings.xml file from the default res/values/ folder in there and translate the values.

Once this is done you can just get the right String by adding @string/some_example_string in the layout files or R.string.some_example_string in the Java files. The app will check what the device's language is and check for strings.xml file in the right values folder. If it can't find it, it will just use the strings.xml file in the default values folder.

Raw

This is not only applicable to the values folder. For example, I'm building an app for this thesis I'm writing. It will contain pretty large articles so all this text should be available in Dutch (my mother tongue) and English. I've decided to place these text files in the res/raw/ directory. Just like the values folders, I can create a different raw folder for each language. The files are then available by referring to R.raw.some_example_text_file. In the example below, I got my text by putting getResources().openRawResource(R.raw.introduction) in my Java code. This can also come in handy if you have images that should be different in according to the language of the device (example: a flag).

Here's an example of how these files and folders are structured.
Notice that there are other files (dimens.xml & styles.xml) in the default values folder but not in the other ones. This is because I don't need to have different dimensions and styles for using another language.

Hope you liked this post and feel free to comment below!

No comments:

Post a Comment