Android official documentation: (3) resources-3.5 Resource Localization

Source: Internet
Author: User
Tags unsupported contact form home screen

Android will run on your devices in your regions. to reach the most users, your application shoshould handle text, audio files, numbers, currency, andgraphics in ways appropriate to the locales where your application will be used.

This document describes best practices for localizing Androidapplications. The principles apply whether you are developing your application using ADT with Eclipse, Ant-based tools, or any other IDE.

You shoshould already have a working knowledge of Java and be familiar withAndroid resource loading, the declaration of user interface elements in XML, development considerations such as Activity lifecycle, and general principles organization and localization.

It is good practice to use the Android resource framework to separate thelocalized aspects of your application as much as possible from the core Javafunctionality:

  • You can put most or all ofContentsOf your application 'suser interface into resource files, as described in this document and in Providing Resources.
  • TheBehaviorOf the user interface, on the other hand, is drivenby your Java code. for example, if users input data that needs to be formatted or sorteddifferently depending on locale, then you wocould use Java to handle the dataprogrammatically. this document does not cover how to localize your Java code.

For a short guide to localizing strings in your app, see the training lesson, Supporting Different versions.

Overview: Resource-Switching in Android

Resources are text strings, layouts, sounds, graphics, and any other staticdata that your Android application needs. an application can include multiplesets of resources, each customized for a different device configuration. when auser runs the application, Android automatically selects and loads the resources that best match the device.

(This document focuses on localization and locale. for a complete descriptionof resource-switching and all the types of deployments that you canspecify-screen orientation, touchscreen type, and so on-see ProvidingAlternative Resources .)

When you write your application:

You create a set of default resources, plus alternatives to be used in different locales.

When a user runs your application:

The Android system selects which resources to load, based on the device's locale.

When you write your application, you create default and alternative resourcesfor your application to use. To create resources, you place files withinspecially named subdirectories of the project'sres/Directory.

Why Default Resources Are Important

Whenever the application runs in a locale for which you have not providedlocale-specific text, Android will load the default strings fromres/values/strings.xml. If this default file is absent, or if it is missing a string that your application needs, then your application will not run and will show an error. the example below has strates what can happen when the default text file is incomplete.

Example:

An application's Java code refers to just two strings,text_aAndtext_b. This application has des a localized resource file (res/values-en/strings.xml) That definestext_aAndtext_bIn English. This application also has des a default resource file (res/values/strings.xml) That includes des adefinitiontext_a, But nottext_b:

  • This application might compile without a problem. An IDE such as Eclipse will not highlight any errors if a resource is missing.
  • When this application is launched on a device with locale set to English, the application might run without a problem, becauseres/values-en/strings.xmlContains both of the needed text strings.
  • However,The user will see an error message and a Force Close buttonWhen this application is launched on a device set to a language other than English. The application will not load.

To prevent this situation, make sure thatres/values/strings.xmlFile exists and that it defines every needed string. the situation applies to all types of resources, not just strings: You need to create a set of default resource files containing all the resources that your application CILS upon-layouts, drawables, animations, etc. for information about testing, see Testing for Default Resources.

Using Resources for Localization How to Create Default Resources

Put the application's default text ina file with the following location and name:

    res/values/strings.xml(Required directory)

The text strings inres/values/strings.xmlShocould use thedefault language, which is the language that you need CT most of your application's users tospeak.

The default resource set must also include any default drawables and layouts, and can include other types of resources such as animations.
    res/drawable/(Required directory holding at least one graphic file, for the application's icon on Google Play)
    res/layout/(Required directory holding an XML file that defines the default layout)
    res/anim/(Required if you have anyres/anim-<qualifiers>Folders)
    res/xml/(Required if you have anyres/xml-<qualifiers>Folders)
    res/raw/(Required if you have anyres/raw-<qualifiers>Folders)

Tip:In your code, examine each reference to an Android resource. Make sure that a default resource is defined for eachone. Also make sure that the default string file is complete:LocalizedString file can contain a subset of the strings, butDefaultString file must contain them all.

How to Create Alternative Resources

A large part of localizing an application is providing alternative text fordifferent versions. In some cases you will also provide alternative graphics, sounds, layouts, and other locale-specific resources.

An application can specify metricsres/<qualifiers>/Directories, each with different qualifiers. to create an alternative resource fora different locale, you use a qualifier that specifies a language or a language-region combination. (The name of a resource directory must conform to the naming scheme described in ProvidingAlternative Resources, or else it will not compile .)

Example:

Suppose that your application's default language is English. suppose alsothat you want to localize all the text in your application to French, and mostof the text in your application (everything doesn't the application's title) toJapanese. in this case, you cocould create three alternativestrings.xmlFiles, each stored in a locale-specific resource directory:

If your Java code refersR.string.title, Here is what willhappen at runtime:

  • If the device is set to any language other than French, Android will loadtitleFromres/values/strings.xmlFile.
  • If the device is set to French, Android will loadtitleFromtheres/values-fr/strings.xmlFile.

Notice that if the device is set to Japan, Android will looktitleInres/values-ja/strings.xmlFile. Butbecause no such string is stored in that file, Android will fall back to thedefault, and will loadtitleIn English fromres/values/strings.xmlFile.

Which Resources Take Precedence?

If multiple resource files match a device's configuration, Android follows aset of rules in deciding which file to use. Among the qualifiers that can bespecified in a resource directory name,Locale almost always takesprecedence.

Example:

Assume that an application between des a default set of graphics and two othersets of graphics, each optimized for a different device setup:

  • res/drawable/
    Contains default graphics.
  • res/drawable-small-land-stylus/
    Contains graphics optimized for use with a device that expects input from a stylus and has a QVGA low-density screen in landscape orientation.
  • res/drawable-ja/
    Contains graphics optimized for use with Japan.

If the application runs on a device that is configured to use Japanese, Android will load graphics fromres/drawable-ja/, Even if thedevice happens to be one that expects input from a stylus and has a QVGA low-density screen in landscape orientation.

Exception:The only qualifiers that takeprecedence over locale in the selection process are MCC and MNC (mobile countrycode and mobile network code ).

Example:

Assume that you have the following situation:

  • The application code CILSR.string.text_a
  • Two relevant resource files are available:
    • res/values-mcc404/strings.xml, Which includestext_aIn the application's default language, in this caseEnglish.
    • res/values-hi/strings.xml, Which includestext_aIn Hindi.
  • The application is running on a device that has the followingconfiguration:
    • The SIM card is connected to a mobile network in India (MCC 404 ).
    • The language is set to Hindi (hi).

Android will loadtext_aFromres/values-mcc404/strings.xml(In English), even if the device isconfigured for Hindi. That is because in the resource-selection process, Androidwill prefer an MCC match over a language match.

The selection process is not always as straightforward as these examplessuggest. please read How Android Findsthe Best-matching Resource for a more nuanced description of theprocess. all the qualifiers are described and listed in order ofprecedence in Table 2 of ProvidingAlternative Resources.

Referring to Resources in Java

In your application's Java code, you refer to resources using the syntaxR.resource_type.resource_nameOrandroid.R.resource_type.resource_name.For more about this, see Accessing Resources.

Localization Checklist

For a complete overview of the process of localizing and distributing an Android application, see the LocalizationChecklist document.

Localization Tips Design your application to work in any locale

You cannot assume anything about the device on which a user willrun your application. the device might have hardware that you were notanticipating, or it might be set to a locale that you did not plan for or that you cannot test. design your application so that it will function normally or fail gracefully no matter what device it runs on.

Important:Make sure that your applicationincludes a full set of default resources.

Make sure to includeres/drawable/Andres/values/Folders (without anyadditional modifiers in the folder names) that contain all the images and textthat your application will need.

If an application is missing even one default resource, it will not run on a device that is set to an unsupported locale. For example,res/values/strings.xmlDefault file might lack one string that the application needs: When the application runs in an unsupported locale and attempts to loadres/values/strings.xml, The user will see an error message and a Force Close button. an IDE such as Eclipse will not highlight this kind of error, and you will not see the problem when you test the application on a device or emulator that is set to a supported locale.

For more information, see Testing for Default Resources.

Design a flexible layout

If you need to rearrange your layout to fit a certain language (for exampleGerman with its long words), you can create an alternative layout for thatlanguage (for exampleres/layout-de/main.xml). However, doing thiscan make your application harder to maintain. It is better to create a singlelayout that is more flexible.

Another typical situation is a language that requires something different inits layout. for example, you might have a contact form that shoshould include twoname fields when the application runs in Japan, but three name fields whenthe application runs in some other language. you coshould handle this in either oftwo ways:

  • Create one layout with a field that you can programmatically enable ordisable, based on the language, or
  • Have the main layout include another layout that includes des the changeablefield. The second layout can have different distributions for differentages.
Avoid creating more resource files and text strings than you need

You probably do not need to create a locale-specificalternative for every resource in your application. For example, the layoutdefined inres/layout/main.xmlFile might work in any locale, in which case there wocould be no need to create any alternative layout files.

Also, you might not need to create alternative text for everystring. For example, assume the following:

  • Your application's default language is AmericanEnglish. Every string that the application uses is defined, using AmericanEnglish spellings, inres/values/strings.xml.
  • For a few important phrases, you want to providebriish English spelling. You want these alternative strings to be used when yourapplication runs on a device in the United Kingdom.

To do this, you cocould create a small file calledres/values-en-rGB/strings.xmlThat between des only the strings thatshoshould be different when the application runs in the U. K. For all the rest ofthe strings, the application will fall back to the defaults and use what isdefined inres/values/strings.xml.

Use the Android Context object for manual locale lookup

You can look up the locale usingContextObjectthat Android makes available:

String locale = context.getResources().getConfiguration().locale.getDisplayName();
Testing Localized Applications Testing on a Device

Keep in mind that the device you are testing may be significantly different from the devices available to consumers in other geographies. the locales available on your device may differ from those available on other devices. also, the resolution and density of the device screen may differ, which cocould affect the display of strings and drawables in your UI.

To change the locale on a device, use the Settings application (Home> Menu> Settings> Locale & text> Select locale ).

Testing on an Emulator

For details about using the emulator, see Android Emulator.

Creating and using a custom locale

A "custom" locale is a language/region combination that the Androidsystem image does not explicitly support. (For a list of supported locales inAndroid platforms see the Version Notes in the SDK tab ). you can testhow your application will run in a custom locale by creating a custom locale inthe emulator. there are two ways to do this:

  • Use the Custom Locale application, which is accessible from theApplication tab. (After you create a custom locale, switch to it by pressing and holding the locale name .)
  • Change to a custom locale from the adb shell, as described below.

When you set the emulator to a locale that is not available in the Androidsystem image, the system itself will display in its default language. Yourapplication, however, shocould localize properly.

Changing the emulator locale from the adb shell

To change the locale in the emulator by using the adb shell.

For instance, to test in Canadian French:

setprop persist.sys.language fr;setprop persist.sys.countryCA;stop;sleep 5;start

This will cause the emulator to restart. (It will look like a full reboot, but it is not .) once the Home screen appears again, re-launch your application (forexample, click the Run icon in Eclipse), and the application will launch withthe new locale.

Testing for Default Resources

Here's how to test whether an application provided des every string resource that it needs:

If the test is successful, repeat it for other types of deployments. For example, if the application has a layout file calledres/layout-land/main.xmlBut does not contain a file calledres/layout-port/main.xml, Then set the emulator or device to portrait orientation and see if the application will run.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.