When we speak about application or game localization (or L10N, which means L followed by 10 letters and N), we generally mean supporting multiple languages. Another term is internationalization (or I18N), which means adapting the game to different regions. An example of I18N would be supporting both metric and imperial systems of units or supporting multiple date formats.
Localization in Android is very simple. The first step is to keep all the strings separate from the code. Instead of hardcoding Hello world!
, we put this string into an XML resource file called strings.xml
. This file is located at res/values/
.
When we created the application, the Eclipse new app wizard already put some strings there. The following code shows how the file should look:
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">LearningAndEngine</string> <string name="action_settings">Settings</string> <string name="hello_world">Hello world!</string> </resources>
Each string has a name that we use to identify it in the code. It's important to use a self-explanatory name. The value is then the real string that will be printed to the screen. Instead of a hardcoded string, we then use the following:
Toast.makeText(activity, activity.getString(R.string.hello_world), Toast.LENGTH_LONG).show();
The getString()
method is used to retrieve the string based on an integer constant. These constants are located in a generated class simply called R
. This class is generated automatically based on the XML file.
To add another language, simply create a folder named res/values-code
, where code
is the language code, for example, de
for German, es
for Spanish, or cs
for Czech. Then, copy the strings.xml
file to the folder and translate the values to the desired language.
The file in the values directory serves as a default fallback option. The other language files don't have to contain all values from the default file. Let's say the application is running on a Spanish language phone, and we have only translated the hello_world
string. Android will automatically use the language file based on the settings of the phone. But, when the application requests the app_name
string, the value is not found in the Spanish language file and the value from the default file will be returned. If the application is running on a device with language settings that are not supported by the game at all, the default values will be used too.
The following screenshot shows the directory structure, and the new language file looks for the Czech language:
3.143.255.36