总结
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)来引用。
[
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:
例如,默认的UI layout是保存在res/layout下的,当屏幕是landscape orientation时,我们也许想指定一个不同的UI layout,保存在res/layout-land/文件夹下。Android能通过比较手机当前的设定和res文件夹的名称自动选择合适的资源。
下面详细讲述了应该如何管理资源文件夹。
我们应该把每种不同的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 projectres/
directory.
Directory | Resource 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 (
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 However, if you need access to original file names and file hierarchy, you might consider saving some resources in the |
values/ |
XML files that contain simple values, such as strings, integers, and colors. Whereas XML resource files in other 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:
res/
named in the form -
.
is the directory name of the corresponding default resources (defined in table 1).
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
. Separate each one with a dash.
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 .
Qualifier | Values | Description |
---|---|---|
MCC and MNC | Examples: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, 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 |
Language and region | Examples: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 " The codes are not case-sensitive; the 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 |
Screen size | small normal large xlarge |
Added in API Level 4. See Supporting Multiple Screens for more information. Also see the |
Screen aspect | long notlong |
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 |
Screen orientation | port land |
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 |
Dock mode | car desk |
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 |
Night mode | night notnight |
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 |
Screen pixel density (dpi) | ldpi mdpi hdpi xhdpi nodpi |
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 |
Also see the |
Keyboard availability | keysexposed keyssoft |
If you provide 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 |
Primary text input method | nokeys qwerty 12key |
Also see the |
Navigation key availability | navexposed navhidden |
This can change during the life of your application if the user reveals the navigation keys. See Handling Runtime Changes for information about how this affects your application during runtime. Also see the |
Primary non-touch navigation method | nonav dpad trackball wheel |
Also see the |
System Version (API Level) | Examples:v3 v4 v7 etc. |
The API Level supported by the device. For example, 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. |
Here are some rules about using configuration qualifier names:
drawable-en-rUS-land
applies to US-English devices in landscape orientation.drawable-hdpi-port/
drawable-port-hdpi/
res/drawable/drawable-en/
.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).
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
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.)
To create an alias to an existing drawable, use the
element. For example:
xml version
=
"1.0"
encoding
=
"utf-8"
?>
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/
).
To create an alias to an existing layout, use the
element, wrapped in a
. For example:
xml version
=
"1.0"
encoding
=
"utf-8"
?>
layout
=
"@layout/main_ltr"
/>
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.
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"
?>
name
="hello"
>
Hello
name
=
"hi"
>
@string/hello
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"
?>
name
=
"yellow"
>
#f00
name
=
"highlight"
>
@color/red
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.
Android 1.5 (and lower) does not support the following configuration qualifers:
ldpi
,
mdpi
,
ldpi
, and
nodpi
small
,
normal
, and
large
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:
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.
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.
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:
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.
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 .
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/
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 .
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:
string
, drawable
, and layout
. For more about the different types, see Resource Types . android:name
attribute, if the resource is a simple value (such as a string).There are two ways you can access a resource:
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 .
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 .
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()
.
While uncommon, you might need access your original files and directories. If you do, then saving your files in res/
won't work for you, because the only way to read a resource from res/
is with the resource ID. Instead, you can save your resources in the assets/
directory.
Files saved in the assets/
directory are not given a resource ID, so you can't reference them through the R
class or from XML resources. Instead, you can query files in the assets/
directory like a normal file system and read raw data using AssetManager
.
However, if all you require is the ability to read raw data (such as a video or audio file), then save the file in the res/raw/
directory and read a stream of bytes using openRawResource()
.
Here's the syntax to reference a resource in code:
[
.]R.
.
is the name of the package in which the resource is located (not required when referencing resources from your own package).
is the R
subclass for the resource type.
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.
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:
// Load a background for the current screen from a drawable resource getWindow().setBackgroundDrawableResource(R.drawable.my_background_image) ; // Set the Activity title by getting a string from the Resources object, because // this method requires a CharSequence rather than a resource ID getWindow().setTitle(getResources().getText(R.string.main_title)); // Load a custom layout for the current screen setContentView(R.layout.main_screen); // Set a slide in animation by getting an Animation from the Resources object mFlipper.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.hyperspace_in)); // Set the text on a TextView object using a resource ID TextView msgTextView = (TextView) findViewById(R.id.msg); msgTextView.setText(R.string.hello_message);
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.
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:
Here is the syntax to reference a resource in an XML resource:
@[
:]
/
is the name of the package in which the resource is located (not required when referencing resources from the same package)
is the R
subclass for the resource type
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.
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"
?>
name
=
"opaque_red"
>
#f00
name
=
"hello"
>
Hello!
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"
?>
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"
?>
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"
?>
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 .
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:
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.
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 .)
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:
Allow your Activity to restart when a configuration changes, but carry a stateful Object
to the new instance of your Activity.
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.
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:
onRetainNonConfigurationInstance()
method to return the Object you would like to retain.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.
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
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:
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:
@Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); // Checks the orientation of the screen if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) { Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show(); } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){ Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show(); } // Checks whether a hardware keyboard is available if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO) { Toast.makeText(this, "keyboard visible", Toast.LENGTH_SHORT).show(); } else if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_YES) { Toast.makeText(this, "keyboard hidden", Toast.LENGTH_SHORT).show(); } }
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
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:
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.
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: |
When a user runs your application: |
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.
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
:
res/values-en/strings.xml
contains both of the needed text strings.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 .
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-
folders) res/xml/
(required if you have any res/xml-
folders) res/raw/
(required if you have any res/raw-
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.
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/
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:
res/values/strings.xml
title
.res/values-fr/strings.xml
title
.res/values-ja/strings.xml
title
. If your Java code refers to R.string.title
, here is what will happen at runtime:
title
from the res/values/strings.xml
file.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.
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/
res/drawable-small-land-stylus/
res/drawable-ja/
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:
R.string.text_a
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.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 .
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 .
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 .
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:
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:
res/values/strings.xml
. 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
.
You can look up the locale using the Context
object that Android makes available:
String
locale
=
context
.
getResources
().
getConfiguration
().
locale
.
getDisplayName
();
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).
For details about using the emulator, see See Android Emulator .
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:
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.
To change the locale in the emulator by using the adb shell.
fr
for French and CA
for Canada. adb shell
-e
option:adb -e shell
#
), 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.
Here's how to test whether an application includes every string resource that it needs:
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.)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.
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:
These checklists summarize the process of localizing an Android application. Not everything on these lists will apply to every application.
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? | |
Identify everything in your application that will need to be localized:
|
|
Design your Java code to externalize resources wherever possible:
|
Create a full set of default resources in res/values/ and other res/ folders, as described in Creating Default Resources . |
|
Obtain reliable translations of the static text, including menu text, button names, error messages, and help text. Place the translated strings in res/values- files. |
|
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. | |
If necessary, create locale-specific versions of your graphics and layout, and place them in res/drawable- and res/layout- folders. |
|
Create any other localized content that your application requires; for example, create recordings of sound files for each language, as needed. |
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. | |
Test the default resources by loading a locale that is not available on the device or emulator. For instructions, see Testing for Default Resources . | |
Test the localized strings in both landscape and portrait display modes. | |
Sign your application and create your final build or builds. | |
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:
res/anim/
and accessed from the
R.anim
class.
res/drawable/
and accessed from the
R.drawable
class.
res/color/
and accessed from the
R.color
class.
res/drawable/
and accessed from the
R.drawable
class.
res/layout/
and accessed from the
R.layout
class.
res/menu/
and accessed from the
R.menu
class.
res/values/
and accessed from the
R.string
,
R.array
, and
R.plurals
classes.
res/values/
and accessed from the
R.style
class.
res/values/
but each accessed from unique
R
sub-classes (such as
R.bool
,
R.integer
,
R.dimen
, etc.)