Application Resources

Resources

总结

android 为不同用途性质的问价设置预先命名文件夹名称。如,drawable, raw,layout等等。文件夹的名称如drawable-hdpi表示为hd屏幕使用的。drawable-hdpi的名称顺序不可以改变。

 

Resource ID 由Resource type(如string, drawable etc) + resource name (filename without the extension) 或xml中的android:name的值(如 string)来引用。

                 [<package-name>].R.[resource type].[resource name]

 

In order to provide compatibility with different configurations of devices, we must organize resources in your project's res/ directory, using various sub-directories that group resources by type and configuration.

 

For any type of resource, we can specigy default and multiple alternative resources for your application:

  • Default resource: are those that should be used regardless of the device configuration or when there are no alternative resources that match the current configuration.
  • Alternative resources are those that you've designed for use with a specific configuration. To specify that a group of resources are for a specific configuration, append an appropriate configuration qualifier to the directory name.

例如,默认的UI layout是保存在res/layout下的,当屏幕是landscape orientation时,我们也许想指定一个不同的UI layout,保存在res/layout-land/文件夹下。Android能通过比较手机当前的设定和res文件夹的名称自动选择合适的资源。

 

下面详细讲述了应该如何管理资源文件夹。

  1. Providing Resources

 

 

我们应该把每种不同的resource放到不同的res/文件夹的子文件夹下。下面是一个简单的项目的文件结构

MyProject/

src/

MyActivity.java



res/

drawable/

icon.png



 layout/

main.xml



info.xml


values/

strings.xml





我们可以看到res/包含一个图片和一个layout.xml. res/文件夹的名称在下表列出




Table 1.


Resource directories supported inside project res/
directory.
DirectoryResource Type
anim/ XML files that define tween animations. See Animation Resources .
color/ XML files that define a state list of colors. See Color State List Resource
drawable/

Bitmap files (.png , .9.png , .jpg , .gif ) or XML files that are compiled into the following drawable resource subtypes:

  • Bitmap files
  • Nine-Patches (re-sizable bitmaps)
  • State lists
  • Shapes
  • Animation drawables
  • Other drawables

See Drawable Resources .

layout/ XML files that define a user interface layout. See Layout Resource .
menu/ XML files that define application menus, such as an Options Menu, Context Menu, or Sub Menu. See Menu Resource .
raw/

Arbitrary files to save in their raw form. To open these resources with a raw InputStream , call Resources.openRawResource() with the resource ID, which is R.raw.filename .

However, if you need access to original file names and file hierarchy, you might consider saving some resources in the assets/ directory (instead of res/raw/ ). Files in assets/ are not given a resource ID, so you can read them only using AssetManager .

values/

XML files that contain simple values, such as strings, integers, and colors.

Whereas XML resource files in other res/ subdirectories define a single resource based on the XML filename, files in the values/ directory describe multiple resources. For a file in this directory, each child of the <resources> element defines a single resource. For example, a <string> element creates an R.string resource and a <color> element creates an R.color resource.

Because each resource is defined with its own XML element, you can name the file whatever you want and place different resource types in one file. However, for clarity, you might want to place unique resource types in different files. For example, here are some filename conventions for resources you can create in this directory:

See String Resources , Style Resource , and More Resource Types .

xml/ Arbitrary XML files that can be read at runtime by calling Resources.getXML() . Various XML configuration files must be saved here, such as a searchable configuration .


保存在表一中的资源都是默认的资源。也就是,这些资源是应用程序默认的设计和内容。但是加入一个android的机器有比正常大的屏幕的

时候,我们就应该有其他的资源来利用大屏幕;假如机器的语言配设定为其他语言,我们就应该有其他的语言资源设定。

为了为不同的设定提供不同的资源,我们需要提供除了默认资源外的其他的资源。



1. 提供额外的资源


Almost every application should provide alternative resources to support specific device configurations.

For instance, you should include alternative drawable resources for different

screen densities and alternative string resources for different languages. At runtime, Android

detects the current device configuration and loads the appropriate

resources for your application.

To specify configuration-specific alternatives for a set of resources:
  1. Create a new directory in res/ named in the form <resources_name> -<config_qualifier> .
    • <resources_name> is the directory name of the corresponding default resources (defined in table 1).
    • <qualifier> is a name that specifies an individual configuration for which these resources are to be used (defined in table 2).

    You can append more than one <qualifier> . Separate each one with a dash.

  2. Save the respective alternative resources in this new directory. The resource files must be named exactly the same as the default resource files.

For example, here are some default and alternative resources:

res/

        drawable/

                 icon.png

                 background.png

         drawable-hdpi/

                 icon.png

                 background.png

 

The hdpi qualifier indicates that the resources in that directory are for devices with a high-density screen. The images in each of these drawable directories are sized for a specific screen density, but the filenames are exactly the same. This way, the resource ID that you use to reference the icon.png or background.png image is always the same, but Android selects the version of each resource that best matches the current device, by comparing the device configuration information with the qualifiers in the alternative resource directory name.

Android supports several configuration qualifiers and you can add multiple qualifiers to one directory name, by separating each qualifier with a dash. Table 2 lists the valid configuration qualifiers, in order of precedence—if you use multiple qualifiers for one resource directory, they must be added to the directory name in the order they are listed in the table.

Note: Some configuration qualifiers were added after Android 1.0, so not all versions of Android support all the qualifiers listed in table 2. New qualifiers indicate the version in which they were added. To avoid any issues, always include a set of default resources for resources that your application uses. For more information, see the section about Providing the Best Device Compatibility with Resources .

Table 2. Configuration qualifier names.

QualifierValuesDescription
MCC and MNCExamples:
mcc310
mcc310-mnc004
mcc208-mnc00
etc.

The mobile country code (MCC), optionally followed by mobile network code (MNC) from the SIM card in the device. For example, mcc310 is U.S. on any carrier, mcc310-mnc004 is U.S. on Verizon, and mcc208-mnc00 is France on Orange.

If the device uses a radio connection (GSM phone), the MCC comes from the SIM, and the MNC comes from the network to which the device is connected.

You can also use the MCC alone (for example, to include country-specific legal resources in your application). If you need to specify based on the language only, then use the language and region qualifier instead (discussed next). If you decide to use the MCC and MNC qualifier, you should do so with care and test that it works as expected.

Also see the configuration fields mcc , and mnc , which indicate the current mobile country code and mobile network code, respectively.

Language and regionExamples:
en
fr
en-rUS
fr-rFR
fr-rCA
etc.

The language is defined by a two-letter ISO 639-1 language code, optionally followed by a two letter ISO 3166-1-alpha-2 region code (preceded by lowercase "r ").

The codes are not case-sensitive; the r prefix is used to distinguish the region portion. You cannot specify a region alone.

This can change during the life of your application if the user changes his or her language in the system settings. See Handling Runtime Changes for information about how this can affect your application during runtime.

See Localization for a complete guide to localizing your application for other languages.

Also see the locale configuration field, which indicates the current locale.

Screen size small
normal
large
xlarge
  • small : Screens based on the space available on a low-density QVGA screen. Considering a portrait HVGA display, this has the same available width but less height—it is 3:4 vs. HVGA's 2:3 aspect ratio. Examples are QVGA low density and VGA high density.
  • normal : Screens based on the traditional medium-density HVGA screen. A screen is considered to be normal if it is at least this size (independent of density) and not larger. Examples of such screens a WQVGA low density, HVGA medium density, WVGA high density.
  • large : Screens based on the space available on a medium-density VGA screen. Such a screen has significantly more available space in both width and height than an HVGA display. Examples are VGA and WVGA medium density screens.
  • xlarge : Screens that are considerably larger than the traditional medium-density HVGA screen. In most cases, devices with extra large screens would be too large to carry in a pocket and would most likely be tablet-style devices. Added in API Level 9.

Added in API Level 4.

See Supporting Multiple Screens for more information.

Also see the screenLayout configuration field, which indicates whether the screen is small, normal, or large.

Screen aspect long
notlong
  • long : Long screens, such as WQVGA, WVGA, FWVGA
  • notlong : Not long screens, such as QVGA, HVGA, and VGA

Added in API Level 4.

This is based purely on the aspect ratio of the screen (a "long" screen is wider). This is not related to the screen orientation.

Also see the screenLayout configuration field, which indicates whether the screen is long.

Screen orientation port
land
  • port : Device is in portrait orientation (vertical)
  • land : Device is in landscape orientation (horizontal)

This can change during the life of your application if the user rotates the screen. See Handling Runtime Changes for information about how this affects your application during runtime.

Also see the orientation configuration field, which indicates the current device orientation.

Dock mode car
desk
  • car : Device is in a car dock
  • desk : Device is in a desk dock

Added in API Level 8.

This can change during the life of your application if the user places the device in a dock. You can enable or disable this mode using UiModeManager . See Handling Runtime Changes for information about how this affects your application during runtime.

Night mode night
notnight
  • night : Night time
  • notnight : Day time

Added in API Level 8.

This can change during the life of your application if night mode is left in auto mode (default), in which case the mode changes based on the time of day. You can enable or disable this mode using UiModeManager . See Handling Runtime Changes for information about how this affects your application during runtime.

Screen pixel density (dpi) ldpi
mdpi
hdpi
xhdpi
nodpi
  • ldpi : Low-density screens; approximately 120dpi.
  • mdpi : Medium-density (on traditional HVGA) screens; approximately 160dpi.
  • hdpi : High-density screens; approximately 240dpi.
  • xhdpi : Extra high-density screens; approximately 320dpi. Added in API Level 8
  • nodpi : This can be used for bitmap resources that you do not want to be scaled to match the device density.

Added in API Level 4.

There is thus a 3:4:6 scaling ratio between the three densities, so a 9x9 bitmap in ldpi is 12x12 in mdpi and 18x18 in hdpi.

When Android selects which resource files to use, it handles screen density differently than the other qualifiers. In step 1 of How Android finds the best matching directory (below), screen density is always considered to be a match. In step 4, if the qualifier being considered is screen density, Android selects the best final match at that point, without any need to move on to step 5.

See Supporting Multiple Screens for more information about how to handle screen sizes and how Android might scale your bitmaps.

Touchscreen type notouch
stylus
finger
  • notouch : Device does not have a touchscreen.
  • stylus : Device has a resistive touchscreen that's suited for use with a stylus.
  • finger : Device has a touchscreen.

Also see the touchscreen configuration field, which indicates the type of touchscreen on the device.

Keyboard availability keysexposed
keyssoft
  • keysexposed : Device has a keyboard available. If the device has a software keyboard enabled (which is likely), this may be used even when the hardware keyboard is not exposed to the user, even if the device has no hardware keyboard. If no software keyboard is provided or it's disabled, then this is only used when a hardware keyboard is exposed.
  • keyshidden : Device has a hardware keyboard available but it is hidden and the device does not have a software keyboard enabled.
  • keyssoft : Device has a software keyboard enabled, whether it's visible or not.

If you provide keysexposed resources, but not keyssoft resources, the system uses the keysexposed resources regardless of whether a keyboard is visible, as long as the system has a software keyboard enabled.

This can change during the life of your application if the user opens a hardware keyboard. See Handling Runtime Changes for information about how this affects your application during runtime.

Also see the configuration fields hardKeyboardHidden and keyboardHidden , which indicate the visibility of a hardware keyboard and and the visibility of any kind of keyboard (including software), respectively.

Primary text input method nokeys
qwerty
12key
  • nokeys : Device has no hardware keys for text input.
  • qwerty : Device has a hardware qwerty keyboard, whether it's visible to the user or not.
  • 12key : Device has a hardware 12-key keyboard, whether it's visible to the user or not.

Also see the keyboard configuration field, which indicates the primary text input method available.

Primary non-touch navigation method nonav
dpad
trackball
wheel
  • nonav : Device has no navigation facility other than using the touchscreen.
  • dpad : Device has a directional-pad (d-pad) for navigation.
  • trackball : Device has a trackball for navigation.
  • wheel : Device has a directional wheel(s) for navigation (uncommon).

Also see the navigation configuration field, which indicates the type of navigation method available.

System Version (API Level)Examples:
v3
v4
v7
etc.

The API Level supported by the device. For example, v1 for API Level 1 (devices with Android 1.0 or higher) and v4 for API Level 4 (devices with Android 1.6 or higher). See the Android API Levels document for more information about these values.

Caution: Android 1.5 and 1.6 only match resources with this qualifier when it exactly matches the system version. See the section below about Known Issues for more information.

 

Qualifier name rules

Here are some rules about using configuration qualifier names:

  • You can specify multiple qualifiers for a single set of resources, separated by dashes. For example, drawable-en-rUS-land applies to US-English devices in landscape orientation.
  • The qualifiers must be in the order listed in table 2 . For example:
    • Wrong: drawable-hdpi-port/
    • Correct: drawable-port-hdpi/
  • Alternative resource directories cannot be nested. For example, you cannot have res/drawable/drawable-en/ .
  • Values are case-insensitive. The resource compiler converts directory names to lower case before processing to avoid problems on case-insensitive file systems. Any capitalization in the names is only to benefit readability.
  • Only one value for each qualifier type is supported. For example, if you want to use the same drawable files for Spain and France, you cannot have a directory named drawable-rES-rFR/ . Instead you need two resource directories, such as drawable-rES/ and drawable-rFR/ , which contain the appropriate files. However, you are not required to actually duplicate the same files in both locations. Instead, you can create an alias to a resource. See Creating alias resources below.

After you save alternative resources into directories named with these qualifiers, Android automatically applies the resources in your application based on the current device configuration. Each time a resource is requested, Android checks for alternative resource directories that contain the requested resource file, then finds the best-matching resource (discussed below). If there are no alternative resources that match a particular device configuration, then Android uses the corresponding default resources (the set of resources for a particular resource type that does not include a configuration qualifier).

 

Creating alias resources

When you have a resource that you'd like to use for more than one device configuration (but do not want to provide as a default resource), you do not need to put the same resource in more than one alternative resource directory. Instead, you can (in some cases) create an alternative resource that acts as an alias for a resource saved in your default resource directory.

Note: Not all resources offer a mechanism by which you can create an alias to another resource. In particular, animation, menu, raw, and other unspecified resources in the xml/ directory do not offer this feature.

For example, imagine you have an application icon, icon.png , and need unique version of it for different locales. However, two locales, English-Canadian and French-Canadian, need to use the same version. You might assume that you need to copy the same image into the resource directory for both English-Canadian and French-Canadian, but it's not true. Instead, you can save the image that's used for both as icon_ca.png (any name other than icon.png ) and put it in the default res/drawable/ directory. Then create an icon.xml file in res/drawable-en-rCA/ and res/drawable-fr-rCA/ that refers to the icon_ca.png resource using the <bitmap> element. This allows you to store just one version of the PNG file and two small XML files that point to it. (An example XML file is shown below.)

Drawable

To create an alias to an existing drawable, use the <bitmap> element. For example:

<?

xml version
=
"1.0"
encoding
=
"utf-8"
?>


<bitmap
xmlns:android
=
"http://schemas.android.com/apk/res/android"


android:src
=


"WkdWMlpXeHZjR1Z5TG1GdVpISnZhV1F1WTI5dEwyZDFhV1JsTDNSdmNHbGpjeTl5WlhOdmRYSmpaWE1

2UUdSeVlYZGhZbXhsTDJsamIyNWZZMkU9xox"



/>


If you save this file as icon.xml (in an alternative resource directory, such as res/drawable-en-rCA/ ), it is compiled into a resource that you can reference as R.drawable.icon , but is actually an alias for the R.drawable.icon_ca resource (which is saved in res/drawable/ ).

Layout

To create an alias to an existing layout, use the <include> element, wrapped in a <merge> . For example:

<?

xml version
=
"1.0"
encoding
=
"utf-8"
?>


<merge>


<include
layout
=
"@layout/main_ltr"


/>


</merge>


If you save this file as main.xml , it is compiled into a resource you can reference as R.layout.main , but is actually an alias for the R.layout.main_ltr resource.

Strings and other simple values

To create an alias to an existing string, simply use the resource ID of the desired string as the value for the new string. For example:

<?

xml version
=
"1.0"
encoding
=
"utf-8"
?>


<resources>


<string
name
="hello"
>


Hello


</string>


<string
name
=
"hi"
>
@string/hello
</string>


</resources>


The R.string.hi resource is now an alias for the R.string.hello .

Other simple values work the same way. For example, a color:

<?

xml version
=
"1.0"
encoding
=
"utf-8"
?>


<resources>


<color
name
=
"yellow"
>
#f00


</color>


<color
name
=
"highlight"
>
@color/red
</color>


</resources>


Providing the Best Device Compatibility with Resources

In order for your application to support multiple device configurations, it's very important that you always provide default resources for each type of resource that your application uses.

For example, if your application supports several languages, always include a values/ directory (in which your strings are saved) without a language and region qualifier . If you instead put all your string files in directories that have a language and region qualifier, then your application will crash when run on a device set to a language that your strings do not support. But, as long as you provide default values/ resources, then your application will run properly (even if the user doesn't understand that language—it's better than crashing).

Likewise, if you provide different layout resources based on the screen orientation, you should pick one orientation as your default. For example, instead of providing layout resources in layout-land/ for landscape and layout-port/ for portrait, leave one as the default, such as layout/ for landscape and layout-port/ for portrait.

Providing default resources is important not only because your application might run on a configuration you had not anticipated, but also because new versions of Android sometimes add configuration qualifiers that older versions do not support. If you use a new resource qualifier, but maintain code compatibility with older versions of Android, then when an older version of Android runs your application, it will crash if you do not provide default resources, because it cannot use the resources named with the new qualifier. For example, if your minSdkVersion is set to 4, and you qualify all of your drawable resources using night mode (night or notnight , which were added in API Level 8), then an API Level 4 device cannot access your drawable resources and will crash. In this case, you probably want notnight to be your default resources, so you should exclude that qualifier so your drawable resources are in either drawable/ or drawable-night/ .

So, in order to provide the best device compatibility, always provide default resources for the resources your application needs to perform properly. Then create alternative resources for specific device configurations using the configuration qualifiers.

There is one exception to this rule: If your application's minSdkVersion is 4 or greater, you do not need default drawable resources when you provide alternative drawable resources with the screen density qualifier. Even without default drawable resources, Android can find the best match among the alternative screen densities and scale the bitmaps as necessary. However, for the best experience on all types of devices, you should provide alternative drawables for all three types of density. If your minSdkVersion is less than 4 (Android 1.5 or lower), be aware that the screen size, density, and aspect qualifiers are not supported on Android 1.5 or lower, so you might need to perform additional compatibility for these versions.

Providing screen resource compatibility for Android 1.5

Android 1.5 (and lower) does not support the following configuration qualifers:

Density
ldpi , mdpi , ldpi , and nodpi
Screen size
small , normal , and large
Screen aspect
long and notlong

These configuration qualifiers were introduced in Android 1.6, so Android 1.5 (API Level 3) and lower does not support them. If you use these configuration qualifiers and do not provide corresponding default resources, then an Android 1.5 device might use any one of the resource directories named with the above screen configuration qualifiers, because it ignores these qualifiers and uses whichever otherwise-matching drawable resource it finds first.

For example, if your application supports Android 1.5 and includes drawable resources for each density type (drawable-ldpi/ , drawable-mdpi/ , and drawable-ldpi/ ), and does not include default drawable resources (drawable/ ), then an Android 1.5 will use drawables from any one of the alternative resource directories, which can result in a user interface that's less than ideal.

 

So, to provide compatibility with Android 1.5 (and lower) when using the screen configuration qualifiers:

  1. Provide default resources that are for medium-density, normal, and notlong screens.

    Because all Android 1.5 devices have medium-density, normal, not-long screens, you can place these kinds of resources in the corresponding default resource directory. For example, put all medium density drawable resources in drawable/ (instead of drawable-mdpi/ ), put normal size resources in the corresponding default resource directory, and notlong resources in the corresponding default resource directory.

  2. Ensure that your SDK Tools version is r6 or greater.

    You need SDK Tools, Revision 6 (or greater), because it includes a new packaging tool that automatically applies an appropriate version qualifier to any resource directory named with a qualifier that does not exist in Android 1.0. For example, because the density qualifier was introduced in Android 1.6 (API Level 4), when the packaging tool encounters a resource directory using the density qualifier, it adds v4 to the directory name to ensure that older versions do not use those resources (only API Level 4 and higher support that qualifier). Thus, by putting your medium-density resources in a directory without the mdpi qualifier, they are still accessible by Android 1.5, and any device that supports the density qualifer and has a medium-density screen also uses the default resources (which are mdpi) because they are the best match for the device (instead of using the ldpi or hdpi resources).

Note: Later versions of Android, such as API Level 8, introduce other configuration qualifiers that older version do not support. To provide the best compatibility, you should always include a set of default resources for each type of resource that your application uses, as discussed above to provide the best device compatibility.

How Android Finds the Best-matching Resource

When you request a resource for which you provide alternatives, Android selects which alternative resource to use at runtime, depending on the current device configuration. To demonstrate how Android selects an alternative resource, assume the following drawable directories each contain different versions of the same images:

drawable/ drawable-en/ drawable-fr-rCA/ drawable-en-port/ drawable-en-notouch-12key/ drawable-port-ldpi/ drawable-port-notouch-12key/

And assume the following is the device configuration:

Locale = en-GB
Screen orientation = port
Screen pixel density = hdpi
Touchscreen type = notouch
Primary text input method = 12key

By comparing the device configuration to the available alternative resources, Android selects drawables from drawable-en-port . It arrives at this decision using the following logic:

Figure 2. Flowchart of how Android finds the best-matching resource.

  1. Eliminate resource files that contradict the device configuration.

    The drawable-fr-rCA/ directory is eliminated, because it contradicts the en-GB locale.

    drawable/

    drawable-en/

    drawable-fr-rCA/


    drawable-en-port/

    drawable-en-notouch-12key/

    drawable-port-ldpi/

    drawable-port-notouch-12key/



    Exception: Screen pixel density is the one qualifier that is not eliminated due to a contradiction. Even though the screen density of the device is hdpi, drawable-port-ldpi/ is not eliminated because every screen density is considered to be a match at this point. More information is available in the Supporting Multiple Screens document.

  2. Pick the (next) highest-precedence qualifier in the list (table 2 ). (Start with MCC, then move down.)
  3. Do any of the resource directories include this qualifier?
    • If No, return to step 2 and look at the next qualifier. (In the example, the answer is "no" until the language qualifier is reached.)
    • If Yes, continue to step 4.
  4. Eliminate resource directories that do not include this qualifier. In the example, the system eliminates all the directories that do not include a language qualifier:
  5. drawable/
    


    drawable-en/

    drawable-en-port/

    drawable-en-notouch-12key/

    drawable-port-ldpi/


    drawable-port-notouch-12key/


    Exception: If the qualifier in question is screen pixel density, Android selects the option that most closely matches the device screen density. In general, Android prefers scaling down a larger original image to scaling up a smaller original image. See Supporting Multiple Screens .

  6. Go back and repeat steps 2, 3, and 4 until only one directory remains. In the example, screen orientation is the next qualifier for which there are any matches. So, resources that do not specify a screen orientation are eliminated:
    drawable-en-port/

    drawable-en-notouch-12key/
    drawable-en/
    
  7. The remaining directory is drawable-en-port .

Though this procedure is executed for each resource requested, the system further optimizes some aspects. One such optimization is that once the device configuration is known, it might eliminate alternative resources that can never match. For example, if the configuration language is English ("en"), then any resource directory that has a language qualifier set to something other than English is never included in the pool of resources checked (though a resource directory without the language qualifier is still included).

Note: The precedence of the qualifier (in table 2 ) is more important than the number of qualifiers that exactly match the device. For example, in step 4 above, the last choice on the list includes three qualifiers that exactly match the device (orientation, touchscreen type, and input method), while drawable-en has only one parameter that matches (language). However, language has a higher precedence than these other qualifiers, so drawable-port-notouch-12key is out.

To learn more about how to use resources in your application, continue to Accessing Resources .

Known Issues

Android 1.5 and 1.6: Version qualifier performs exact match, instead of best match

The correct behavior is for the system to match resources marked with a version qualifier equal to or less than the system version on the device, but on Android 1.5 and 1.6, (API Level 3 and 4), there is a bug that causes the system to match resources marked with the version qualifier only when it exactly matches the version on the device.

The workaround: To provide version-specific resources, abide by this behavior. However, because this bug is fixed in versions of Android available after 1.6, if you need to differentiate resources between Android 1.5, 1.6, and later versions, then you only need to apply the version qualifier to the 1.6 resources and one to match all later versions. Thus, this is effectively a non-issue.

For example, if you want drawable resources that are different on each Android 1.5, 1.6, and 2.0.1 (and later), create three drawable directories: drawable/ (for 1.5 and lower), drawable-v4 (for 1.6), and drawable-v6 (for 2.0.1 and later—version 2.0, v5, is no longer available).

Accessing Resources

 

Once you provide a resource in your application (discussed in Providing Resources ), you can apply it by referencing its resource ID. All resource IDs are defined in your project's R class, which the aapt tool automatically generates.

When your application is compiled, aapt generates the R class, which contains resource IDs for all the resources in your res/ directory. For each type of resource, there is an R subclass (for example, R.drawable for all drawable resources) and for each resource of that type, there is a static integer (for example, R.drawable.icon ). This integer is the resource ID that you can use to retrieve your resource.

Although the R class is where resource IDs are specified, you should never need to look there to discover a resource ID. A resource ID is always composed of:

  • The resource type : Each resource is grouped into a "type," such as string , drawable , and layout . For more about the different types, see Resource Types .
  • The resource name , which is either: the filename, excluding the extension; or the value in the XML android:name attribute, if the resource is a simple value (such as a string).

There are two ways you can access a resource:

  • In code: Using an static integer from a sub-class of your R class, such as:
    R.string.hello

    string is the resource type and hello is the resource name. There are many Android APIs that can access your resources when you provide a resource ID in this format. See Accessing Resources in Code .

  • In XML: Using a special XML syntax that also corresponds to the resource ID defined in your R class, such as:
    @string/hello

    string is the resource type and hello is the resource name. You can use this syntax in an XML resource any place where a value is expected that you provide in a resource. See Accessing Resources from XML .

2. Accessing Resources in Code

    You can use a resource in code by passing the resource ID as a method parameter. For example, you can set an ImageView to use the res/drawable/myimage.png resource using setImageResource() :

    ImageView
    


    imageView
    =
    (
    ImageView
    )
    findViewById
    (
    R
    .
    id
    .
    myimageview
    );


    imageView
    .
    setImageResource
    (
    R
    .
    drawable
    .
    myimage

    );


    You can also retrieve individual resources using methods in Resources , which you can get an instance of with getResources() .

    Syntax

    Here's the syntax to reference a resource in code:

    [<package_name>
    


    .]R.<resource_type>


    .<resource_name>


    • <package_name> is the name of the package in which the resource is located (not required when referencing resources from your own package).
    • <resource_type> is the R subclass for the resource type.
    • <resource_name> is either the resource filename without the extension or the android:name attribute value in the XML element (for simple values).

    See Resource Types for more information about each resource type and how to reference them.

    Use cases

    There are many methods that accept a resource ID parameter and you can retrieve resources using methods in Resources . You can get an instance of Resources with Context.getResources() .

    Here are some examples of accessing resources in code:

     
    





    Caution: You should never modify the R.java file by hand—it is generated by the aapt tool when your project is compiled. Any changes are overridden next time you compile.

    Accessing Resources from XML

    You can define values for some XML attributes and elements using a reference to an existing resource. You will often do this when creating layout files, to supply strings and images for your widgets.

    For example, if you add a Button to your layout, you should use a string resource for the button text:





    Syntax

    Here is the syntax to reference a resource in an XML resource:

    @[<package_name>
    
    :]<resource_type>
    /<resource_name>


    • <package_name> is the name of the package in which the resource is located (not required when referencing resources from the same package)
    • <resource_type> is the R subclass for the resource type
    • <resource_name> is either the resource filename without the extension or the android:name attribute value in the XML element (for simple values).

    See Resource Types for more information about each resource type and how to reference them.

    Use cases

    In some cases you must use a resource for a value in XML (for example, to apply a drawable image to a widget), but you can also use a resource in XML any place that accepts a simple value. For example, if you have the following resource file that includes a color resource and a string resource :

    <?
    
    xml version
    =
    "1.0"
    encoding
    =
    "utf-8"
    ?>



    <resources>


       

    <color

    name
    =
    "opaque_red"
    >
    #f00
    </color>


       

    <string

    name
    =
    "hello"
    >
    Hello!
    </string>



    </resources>

    You can use these resources in the following layout file to set the text color and text string:



    <?
    xml version
    =
    "1.0"
    encoding
    =
    "utf-8"
    ?>



    <EditText

    xmlns:android
    =
    "http://schemas.android.com/apk/res/android"


       

    android:layout_width
    =
    "fill_parent"


       

    android:layout_height
    =
    "fill_parent"


       

    android:textColor
    =
    "
    @color/opaque_red

    "


       

    android:text
    =
    "
    @string/hello

    "

    />

    In this case you don't need to specify the package name in the resource reference because the resources are from your own package. To reference a system resource, you would need to include the package name. For example:


    <?
    xml version
    =
    "1.0"
    encoding
    =
    "utf-8"
    ?>



    <EditText

    xmlns:android
    =
    "http://schemas.android.com/apk/res/android"


       

    android:layout_width
    =
    "fill_parent"


       

    android:layout_height
    =
    "fill_parent"


       

    android:textColor
    =
    "
    @android:color/secondary_text_dark

    "


       

    android:text
    =
    "@string/hello"

    />

    Note: You should use string resources at all times, so that your application can be localized for other languages. For information about creating alternative resources (such as localized strings), see Providing Alternative Resources .

    You can even use resources in XML to create aliases. For example, you can create a drawable resource that is an alias for another drawable resource:




    <?
    xml version
    =
    "1.0"
    encoding
    =
    "utf-8"
    ?>



    <bitmap

    xmlns:android
    =
    "http://schemas.android.com/apk/res/android"


       

    android:src
    =
    "WkdWMlpXeHZjR1Z5TG1GdVpISnZhV1F1WTI5dEwyZDFhV1JsTDNSdmNHbGpjeTl5WlhOdmRYSmpa

    WE12UUdSeVlYZGhZbXhsTDI5MGFHVnlYMlJ5WVhkaFlteGw=xox"


    />

    This sounds redundant, but can be very useful when using alternative resource. Read more about Creating alias resources .

    Referencing style attributes

    A style attribute resource allows you to reference the value of an attribute in the currently-applied theme. Referencing a style attribute allows you to customize the look of UI elements by styling them to match standard variations supplied by the current theme, instead of supplying a hard-coded value. Referencing a style attribute essentially says, "use the style that is defined by this attribute, in the current theme."

    To reference a style attribute, the name syntax is almost identical to the normal resource format, but instead of the at-symbol (@ ), use a question-mark (? ), and the resource type portion is optional. For instance:

    ?[
    
    <
    package_name
    >

    :][
    <
    resource_type
    >

    /]
    <
    resource_name
    >





    For example, here's how you can reference an attribute to set the text color to match the
    "primary" text color of the system theme:
    <EditText
    

    id
    =
    "text"


    android:layout_width
    =
    "fill_parent"


    android:layout_height
    =
    "wrap_content"



    android:textColor
    =
    "
    ?android:textColorSecondary

    "


     
    android:text
    =
    "@string/hello_world"
    />


    Here, the android:textColor attribute specifies the name of a style attribute in the current theme. Android now uses the value applied to the android:textColorSecondary style attribute as the value for android:textColor in this widget. Because the system resource tool knows that an attribute resource is expected in this context, you do not need to explicitly state the type (which would be ?android:attr/textColorSecondary )—you can exclude the attr type.

    Accessing Platform Resources

    Android contains a number of standard resources, such as styles, themes, and layouts. To access these resource, qualify your resource reference with the android package name. For example, Android provides a layout resource you can use for list items in a ListAdapter :






    setListAdapter


    (
    new

    ArrayAdapter


    <
    String
    >(
    this
    ,

    android
    .
    R
    .
    layout
    .
    simple_list_item_1

    ,
    myarray
    ));

    In this example, simple_list_item_1 is a layout resource defined by the platform for items in a ListView . You can use this instead of creating your own layout for list items. (For more about using ListView , see the List View Tutorial .)

    Handling Runtime Changes

     

    Some device configurations can change during runtime (such as screen orientation, keyboard availability, and language). When such a change occurs, Android restarts the running Activity (onDestroy() is called, followed by onCreate() ). The restart behavior is designed to help your application adapt to new configurations by automatically reloading your application with alternative resources.

    To properly handle a restart, it is important that your Activity restores its previous state through the normal Activity lifecycle , in which Android calls onSaveInstanceState() before it destroys your Activity so that you can save data about the application state. You can then restore the state during onCreate() or onRestoreInstanceState() . To test that your application restarts itself with the application state intact, you should invoke configuration changes (such as changing the screen orientation) while performing various tasks in your application.

    Your application should be able to restart at any time without loss of user data or state in order to handle events such as when the user receives an incoming phone call and then returns to your application (read about the Activity lifecycle ).

    However, you might encounter a situation in which restarting your application and restoring significant amounts of data can be costly and create a poor user experience. In such a situation, you have two options:

    1. Retain an object during a configuration change

      Allow your Activity to restart when a configuration changes, but carry a stateful Object to the new instance of your Activity.

    2. Handle the configuration change yourself

      Prevent the system from restarting your Activity during certain configuration changes and receive a callback when the configurations do change, so that you can manually update your Activity as necessary.

    Retaining an Object During a Configuration Change

    If restarting your Activity requires that you recover large sets of data, re-establish a network connection, or perform other intensive operations, then a full restart due to a configuration change might be an unpleasant user experience. Also, it may not be possible for you to completely maintain your Activity state with the Bundle that the system saves for you during the Activity lifecycle—it is not designed to carry large objects (such as bitmaps) and the data within it must be serialized then deserialized, which can consume a lot of memory and make the configuration change slow. In such a situation, you can alleviate the burden of reinitializing your Activity by retaining a stateful Object when your Activity is restarted due to a configuration change.

    To retain an Object during a runtime configuration change:

    1. Override the onRetainNonConfigurationInstance() method to return the Object you would like to retain.
    2. When your Activity is created again, call getLastNonConfigurationInstance() to recover your Object.

    Android calls onRetainNonConfigurationInstance() between onStop() and onDestroy() when it shuts down your Activity due to a configuration change. In your implementation of onRetainNonConfigurationInstance() , you can return any Object that you need in order to efficiently restore your state after the configuration change.

    A scenario in which this can be valuable is if your application loads a lot of data from the web. If the user changes the orientation of the device and the Activity restarts, your application must re-fetch the data, which could be slow. What you can do instead is implement onRetainNonConfigurationInstance() to return an object carrying your data and then retrieve the data when your Activity starts again with getLastNonConfigurationInstance() . For example:


    @Override



    public

    Object
    onRetainNonConfigurationInstance
    ()

    {


       

    final

    MyDataObject
    data
    =
    collectMyLoadedData
    ();


       

    return
    data
    ;



    }

    Caution: While you can return any object, you should never pass an object that is tied to the Activity , such as a Drawable , an Adapter , a View or any other object that's associated with a Context . If you do, it will leak all the Views and resources of the original Activity instance. (To leak the resources means that your application maintains a hold on them and they cannot be garbage-collected, so lots of memory can be lost.)

    Then retrieve the data when your Activity starts again:


    @Override



    public

    void
    onCreate
    (
    Bundle
    savedInstanceState
    )

    {


       

    super
    .
    onCreate
    (
    savedInstanceState
    );


        setContentView

    (
    R
    .
    layout
    .
    main
    );




       

    final

    MyDataObject
    data
    =

    (
    MyDataObject
    )
    getLastNonConfigurationInstance
    ();


       

    if

    (
    data
    ==

    null
    )

    {


            data

    =
    loadMyData
    ();


       

    }


       

    ...



    }

    In this case, getLastNonConfigurationInstance() retrieves the data saved by onRetainNonConfigurationInstance() . If data is null (which happens when the Activity starts due to any reason other than a configuration change) then the data object is loaded from the original source.

    Handling the Configuration Change Yourself

    If your application doesn't need to update resources during a specific configuration change and you have a performance limitation that requires you to avoid the Activity restart, then you can declare that your Activity handles the configuration change itself, which prevents the system from restarting your Activity.

    Note: Handling the configuration change yourself can make it much more difficult to use alternative resources, because the system does not automatically apply them for you. This technique should be considered a last resort and is not recommended for most applications.

    To declare that your Activity handles a configuration change, edit the appropriate <activity> element in your manifest file to include the android:configChanges attribute with a string value that represents the configuration that you want to handle. Possible values are listed in the documentation for the android:configChanges attribute (the most commonly used values are orientation to handle when the screen orientation changes and keyboardHidden to handle when the keyboard availability changes). You can declare multiple configuration values in the attribute by separating them with a pipe character ("|").

    For example, the following manifest snippet declares an Activity that handles both the screen orientation change and keyboard availability change:


    <activity

    android:name
    =
    ".MyActivity"


             

    android:configChanges
    =
    "orientation|keyboardHidden"


             

    android:label
    =
    "@string/app_name"
    >

    Now when one of these configurations change, MyActivity is not restarted. Instead, the Activity receives a call to onConfigurationChanged() . This method is passed a Configuration object that specifies the new device configuration. By reading fields in the Configuration , you can determine the new configuration and make appropriate changes by updating the resources used in your interface. At the time this method is called, your Activity's Resources object is updated to return resources based on the new configuration, so you can easily reset elements of your UI without the system restarting your Activity.

    For example, the following onConfigurationChanged() implementation checks the availability of a hardware keyboard and the current device orientation:

    
    



    The Configuration object represents all of the current configurations, not just the ones that have changed. Most of the time, you won't care exactly how the configuration has changed and can simply re-assign all your resources that provide alternatives to the configuration that you're handling. For example, because the Resources object is now updated, you can reset any ImageView s with setImageResource(int) and the appropriate resource for the new configuration is used (as described in Providing Resources ).

    Notice that the values from the Configuration fields are integers that are matched to specific constants from the Configuration class. For documentation about which constants to use with each field, refer to the appropriate field in the Configuration reference.

    Remember: When you declare your Activity to handle a configuration change, you are responsible for resetting any elements for which you provide alternatives. If you declare your Activity to handle the orientation change and have images that should change between landscape and portrait, you must re-assign each resource to each element during onConfigurationChanged() .

    If you don't need to update your application based on these configuration changes, you can instead not implement onConfigurationChanged() . In which case, all of the resources used before the configuration change are still used and you've only avoided the restart of your Activity. However, your application should always be able to shutdown and restart with its previous state intact. Not only because there are other configuration changes that you cannot prevent from restarting your application but also in order to handle events such as when the user receives an incoming phone call and then returns to your application.

    For more about which configuration changes you can handle in your Activity, see the android:configChanges documentation and the Configuration class.

    ↑ Go to top

     

    4. Localization

     

     

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

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

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

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

    • You can put most or all of the contents of your application's user interface into resource files, as described in this document and in Providing Resources .
    • The behavior of the user interface, on the other hand, is driven by your Java code. For example, if users input data that needs to be formatted or sorted differently depending on locale, then you would use Java to handle the data programmatically. This document does not cover how to localize your Java code.

    The Hello, L10N tutorial takes you through the steps of creating a simple localized application that uses locale-specific resources in the way described in this document.

    Overview: Resource-Switching in Android

    Resources are text strings, layouts, sounds, graphics, and any other static data that your Android application needs. An application can include multiple sets of resources, each customized for a different device configuration. When a user 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 description of resource-switching and all the types of configurations that you can specify — screen orientation, touchscreen type, and so on — see Providing Alternative Resources .)

    When you write your application:

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

    right-arrow

    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 resources for your application to use. To create resources, you place files within specially named subdirectories of the project's res/ directory.

    Why Default Resources Are Important

    Whenever the application runs in a locale for which you have not provided locale-specific text, Android will load the default strings from res/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 illustrates what can happen when the default text file is incomplete.

    Example:

    An application's Java code refers to just two strings, text_a and text_b . This application includes a localized resource file (res/values-en/strings.xml ) that defines text_a and text_b in English. This application also includes a default resource file (res/values/strings.xml ) that includes a definition for text_a , but not for text_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, because res/values-en/strings.xml contains both of the needed text strings.
    • However, the user will see an error message and a Force Close button when 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 that a res/values/strings.xml file 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 calls 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 in a file with the following location and name:

        res/values/strings.xml (required directory)

    The text strings in res/values/strings.xml should use the default language, which is the language that you expect most of your application's users to speak.

    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 in the Market)
        res/layout/ (required directory holding an XML file that defines the default layout)
        res/anim/ (required if you have any res/anim-<qualifiers> folders)
        res/xml/ (required if you have any res/xml-<qualifiers> folders)
        res/raw/ (required if you have any res/raw-<qualifiers> folders)

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

    How to Create Alternative Resources

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

    An application can specify many res/<qualifiers> / directories, each with different qualifiers. To create an alternative resource for a 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 Providing Alternative Resources , or else it will not compile.)

    Example:

    Suppose that your application's default language is English. Suppose also that you want to localize all the text in your application to French, and most of the text in your application (everything except the application's title) to Japanese. In this case, you could create three alternative strings.xml files, each stored in a locale-specific resource directory:

    1. res/values/strings.xml
      Contains English text for all the strings that the application uses, including text for a string named title .
    2. res/values-fr/strings.xml
      Contain French text for all the strings, including title .
    3. res/values-ja/strings.xml
      Contain Japanese text for all the strings except title .

    If your Java code refers to R.string.title , here is what will happen at runtime:

    • If the device is set to any language other than French, Android will load title from the res/values/strings.xml file.
    • If the device is set to French, Android will load title from the res/values-fr/strings.xml file.

    Notice that if the device is set to Japanese, Android will look for title in the res/values-ja/strings.xml file. But because no such string is included in that file, Android will fall back to the default, and will load title in English from the res/values/strings.xml file.

    Which Resources Take Precedence?

    If multiple resource files match a device's configuration, Android follows a set of rules in deciding which file to use. Among the qualifiers that can be specified in a resource directory name, locale almost always takes precedence .

    Example:

    Assume that an application includes a default set of graphics and two other sets 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 Japanese.

    If the application runs on a device that is configured to use Japanese, Android will load graphics from res/drawable-ja/ , even if the device 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 take precedence over locale in the selection process are MCC and MNC (mobile country code and mobile network code).

    Example:

    Assume that you have the following situation:

    • The application code calls for R.string.text_a
    • Two relevant resource files are available:
      • res/values-mcc404/strings.xml , which includes text_a in the application's default language, in this case English.
      • res/values-hi/strings.xml , which includes text_a in Hindi.
    • The application is running on a device that has the following configuration:
      • The SIM card is connected to a mobile network in India (MCC 404).
      • The language is set to Hindi (hi ).

    Android will load text_a from res/values-mcc404/strings.xml (in English), even if the device is configured for Hindi. That is because in the resource-selection process, Android will prefer an MCC match over a language match.

    The selection process is not always as straightforward as these examples suggest. Please read How Android Finds the Best-matching Resource for a more nuanced description of the process. All the qualifiers are described and listed in order of precedence in Table 2 of Providing Alternative Resources .

    Referring to Resources in Java

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

    Localization Strategies

    Design your application to work in any locale

    You cannot assume anything about the device on which a user will run your application. The device might have hardware that you were not anticipating, 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 application includes a full set of default resources.

    Make sure to include res/drawable/ and a res/values/ folders (without any additional modifiers in the folder names) that contain all the images and text that 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, the res/values/strings.xml default file might lack one string that the application needs: When the application runs in an unsupported locale and attempts to load res/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 example German with its long words), you can create an alternative layout for that language (for example res/layout-de/main.xml ). However, doing this can make your application harder to maintain. It is better to create a single layout that is more flexible.

    Another typical situation is a language that requires something different in its layout. For example, you might have a contact form that should include two name fields when the application runs in Japanese, but three name fields when the application runs in some other language. You could handle this in either of two ways:

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

    You probably do not need to create a locale-specific alternative for every resource in your application. For example, the layout defined in the res/layout/main.xml file might work in any locale, in which case there would be no need to create any alternative layout files.

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

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

    To do this, you could create a small file called res/values-en-rGB/strings.xml that includes only the strings that should be different when the application runs in the U.K. For all the rest of the strings, the application will fall back to the defaults and use what is defined in res/values/strings.xml .

    Use the Android Context object for manual locale lookup

    You can look up the locale using the Context object that 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 could 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 See Android Emulator .

    Creating and using a custom locale

    A "custom" locale is a language/region combination that the Android system image does not explicitly support. (For a list of supported locales in Android platforms see the Version Notes in the SDK tab). You can test how your application will run in a custom locale by creating a custom locale in the emulator. There are two ways to do this:

    • Use the Custom Locale application, which is accessible from the Application 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 Android system image, the system itself will display in its default language. Your application, however, should localize properly.

    Changing the emulator locale from the adb shell

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

    1. Pick the locale you want to test and determine its language and region codes, for example fr for French and CA for Canada.
    2. Launch an emulator.
    3. From a command-line shell on the host computer, run the following command:
      adb shell
      or if you have a device attached, specify that you want the emulator by adding the -e option:
      adb -e shell
    4. At the adb shell prompt (# ), run this command:
      setprop persist.sys.language [language code ];setprop persist.sys.country [country code ];stop;sleep 5;start
      Replace bracketed sections with the appropriate codes from Step 1.

    For instance, to test in Canadian French:

    setprop persist.sys.language fr;setprop persist.sys.country CA;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 (for example, click the Run icon in Eclipse), and the application will launch with the new locale.

    Testing for Default Resources

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

    1. Set the emulator or device to a language that your application does not support. For example, if the application has French strings in res/values-fr/ but does not have any Spanish strings in res/values-es/ , then set the emulator's locale to Spanish. (You can use the Custom Locale application to set the emulator to an unsupported locale.)
    2. Run the application.
    3. If the application shows an error message and a Force Close button, it might be looking for a string that is not available. Make sure that your res/values/strings.xml file includes a definition for every string that the application uses.

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

    Publishing Localized Applications

    The Android Market is the main application distribution system for Android devices. To publish a localized application, you need to sign your application, version it, and go through all the other steps described in Preparing to Publish .

    If you split your application in several .apk files, each targeted to a different locale, follow these guidelines:

    • Sign each .apk file with the same certificate. For more about this, see Signing Strategies .
    • Give each .apk file a different application name. Currently it is impossible to put two applications into the Android Market that have exactly the same name.
    • Include a complete set of default resources in each .apk file.

    Localization Checklists

    These checklists summarize the process of localizing an Android application. Not everything on these lists will apply to every application.

    Planning and Design Checklist

    arrow Choose a localization strategy. Which countries and which languages will your application support? What is your application's default country and language? How will your application behave when it does not have specific resources available for a given locale?
    arrow

    Identify everything in your application that will need to be localized:

    • Consider specific details of your application — text, images, sounds, music, numbers, money, dates and times. You might not need to localize everything. For example, you don't need to localize text that the user never sees, or images that are culturally neutral, or icons that convey the same meaning in every locale.
    • Consider broad themes. For example, if you hope to sell your application in two very culturally different markets, you might want to design your UI and present your application in an entirely different way for each locale.
    arrow

    Design your Java code to externalize resources wherever possible:

    • Use R.string and strings.xml files instead of hard-coded strings or string constants.
    • Use R.drawable and R.layout instead of hard-coded drawables or layouts.

    Content Checklist

    arrow Create a full set of default resources in res/values/ and other res/ folders, as described in Creating Default Resources .
    arrow Obtain reliable translations of the static text, including menu text, button names, error messages, and help text. Place the translated strings in res/values-<qualifiers> /strings.xml files.
    arrow Make sure that your application correctly formats dynamic text (for example numbers and dates) for each supported locale. Make sure that your application handles word breaks, punctuation, and alphabetical sorting correctly for each supported language.
    arrow If necessary, create locale-specific versions of your graphics and layout, and place them in res/drawable-<qualifiers> / and res/layout-<qualifiers> / folders.
    arrow Create any other localized content that your application requires; for example, create recordings of sound files for each language, as needed.

    Testing and Publishing Checklist

    arrow Test your application for each supported locale. If possible, have a person who is native to each locale test your application and give you feedback.
    arrow Test the default resources by loading a locale that is not available on the device or emulator. For instructions, see Testing for Default Resources .
    arrow Test the localized strings in both landscape and portrait display modes.
    arrow Sign your application and create your final build or builds.
    arrow Upload your .apk file or files to Market, selecting the appropriate languages as you upload. (For more details, see Publishing Your Applications .)

     

    Resource Types

    Each of the documents in this section describe the usage, format and syntax for a certain type of application resource that you can provide in your resources directory (res/ ).

    Here's a brief summary of each resource type:

    Animation Resources
    Define pre-determined animations.
    Tween animations are saved in res/anim/ and accessed from the R.anim class.
    Frame animations are saved in res/drawable/ and accessed from the R.drawable class.
    Color State List Resource
    Define a color resources that changes based on the View state.
    Saved in res/color/ and accessed from the R.color class.
    Drawable Resources
    Define various graphics with bitmaps or XML.
    Saved in res/drawable/ and accessed from the R.drawable class.
    Layout Resource
    Define the layout for your application UI.
    Saved in res/layout/ and accessed from the R.layout class.
    Menu Resource
    Define the contents of your application menus.
    Saved in res/menu/ and accessed from the R.menu class.
    String Resources
    Define strings, string arrays, and plurals (and include string formatting and styling).
    Saved in res/values/ and accessed from the R.string , R.array , and R.plurals classes.
    Style Resource
    Define the look and format for UI elements.
    Saved in res/values/ and accessed from the R.style class.
    More Resource Types
    Define values such as booleans, integers, dimensions, colors, and other arrays.
    Saved in res/values/ but each accessed from unique R sub-classes (such as R.bool , R.integer , R.dimen , etc.)

    评论 2
    添加红包

    请填写红包祝福语或标题

    红包个数最小为10个

    红包金额最低5元

    当前余额3.43前往充值 >
    需支付:10.00
    成就一亿技术人!
    领取后你会自动成为博主和红包主的粉丝 规则
    hope_wisdom
    发出的红包
    实付
    使用余额支付
    点击重新获取
    扫码支付
    钱包余额 0

    抵扣说明:

    1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
    2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

    余额充值