Recipe 11.1 Localizing Your Application

Android Versions
Level 1 and above
Permissions
None
Source Code to Download from Wrox.com
Localization.zip

Most applications today are developed for the world market — it is likely that your application will be used by people residing in countries other than your own. As such, it is important that you make provisions to ensure that your app is easily localizable to other languages. This recipe shows how to localize the UI of your application to display the language with which the user is familiar.

Solution

The first rule of localizing your Android application is to ensure that all the string literals used in the UI of the application are stored in the strings.xml file located in the res/values folder of your project. For example, consider the following activity_main.xml file:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:padding="@dimen/padding_medium"
        android:text="@string/quotation"
        tools:context=".MainActivity" />

</RelativeLayout>

In the preceding example, the string displayed by the TextView is stored as a key named quotation in the strings.xml file (located in the res/values folder), like this: ...

Get Android Application Development Cookbook: 93 Recipes for Building Winning Apps now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.