Multi-Language support and SpinnerPreference – Part I

When I first started Android programming, I felt the best way to learn was to try and implement various features I felt were important in my Windows programming.  So after writing a simple Android notes application, I looked into what it would take to make it multi-language. For added flexibility, I decided to make the app’s language a user setting, which could be independent of the current locale of the device.

In Android, adding support for multiple languages is pretty straight forward: just create separate strings.xml files in values directories appended with a hyphen and the ISO language code inside your applications res directory. For example in Windows:

MyProject\app\src\main\
    res\
       values\
           strings.xml
       values-es\
           strings.xml
       values-fr\
           strings.xml

At runtime, Android will load the correct string file based on the locale set for the device. For more information on this check out Supporting Different Languages

One thing to remember is that string literals are discouraged in Android, which brings up the issue of strings that shouldn’t be translated. To get around this, put all the strings that need to be translated in the language specific strings.xml files and then create a file in the values directory called literals.xml for strings that do not need to be translated. In literals.xml you need to tell the compiler that the strings in the file do not need to be translated which is done by the following line:

<resources xmlns:tools="http://schemas.android.com/tools" 
tools:ignore="MissingTranslation">

To set the locale of the device, the same ISO language code used to name the values directories is used to create a region specific locale that then gets passed to the updateConfiguration function:

Locale locale = new Locale("en");
locale.setDefault(locale);
config.locale = locale;
getBaseContext().getResources().updateConfiguration( config, 
getBaseContext().getResources().getDisplayMetrics());

// Since new language, force the activity to restart
recreate();

In part II we’ll look at saving state in an Android app and preference dialogs.

This entry was posted in Android App Development. Bookmark the permalink.