Providing Resources

来源:互联网 发布:织梦cms后台演示地址 编辑:程序博客网 时间:2024/05/21 00:55

You should always externalize application resources such as images and strings from your code, so that you can maintain them independently. You should also provide alternative resources for specific device configurations, by grouping them in specially-named resource directories. At runtime, Android uses the appropriate resource based on the current configuration. For example, you might want to provide a different UI layout depending on the screen size or different strings depending on the language setting.

Once you externalize your application resources, you can access them using resource IDs that are generated in your project's R class. How to use resources in your application is discussed in Accessing Resources. This document shows you how to group your resources in your Android project and provide alternative resources for specific device configurations.

Grouping Resource Types


You should place each type of resource in a specific subdirectory of your project's res/ directory. For example, here's the file hierarchy for a simple project:

MyProject/    src/          MyActivity.java      res/        drawable/              graphic.png          layout/              main.xml            info.xml        mipmap/              icon.png         values/              strings.xml  

As you can see in this example, the res/ directory contains all the resources (in subdirectories): an image resource, two layout resources, mipmap/ directories for launcher icons, and a string resource file. The resource directory names are important and are described in table 1.

Note: For more information about using the mipmap folders, see Managing Projects Overview.

Table 1. Resource directories supported inside project res/ directory.

DirectoryResource Typeanimator/XML files that define property animations.anim/XML files that define tween animations. (Property animations can also be saved in this directory, but the animator/ directory is preferred for property animations to distinguish between the two types.)color/XML files that define a state list of colors. See Color State List Resourcedrawable/

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.

mipmap/Drawable files for different launcher icon densities. For more information on managing launcher icons with mipmap/ folders, see Managing Projects Overview.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:

  • arrays.xml for resource arrays (typed arrays).
  • colors.xml for color values
  • dimens.xml for dimension values.
  • strings.xml for string values.
  • styles.xml for styles.

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.

Caution: Never save resource files directly inside the res/ directory—it will cause a compiler error.

For more information about certain types of resources, see the Resource Types documentation.

The resources that you save in the subdirectories defined in table 1 are your "default" resources. That is, these resources define the default design and content for your application. However, different types of Android-powered devices might call for different types of resources. For example, if a device has a larger than normal screen, then you should provide different layout resources that take advantage of the extra screen space. Or, if a device has a different language setting, then you should provide different string resources that translate the text in your user interface. To provide these different resources for different device configurations, you need to provide alternative resources, in addition to your default resources.

Providing Alternative Resources


Figure 1. Two different devices, each using different layout resources.

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.

    Caution: When appending multiple qualifiers, you must place them in the same order in which they are listed in table 2. If the qualifiers are ordered wrong, the resources are ignored.

  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 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 a resource directory, you must add them to the directory name in the order they are listed in the table.

Table 2. Configuration qualifier names.

ConfigurationQualifier ValuesDescriptionMCC 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 and MNC values come from the SIM card.

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.

Layout Directionldrtl
ldltr

The layout direction of your application. ldrtl means "layout-direction-right-to-left". ldltr means "layout-direction-left-to-right" and is the default implicit value.

This can apply to any resource such as layouts, drawables, or values.

For example, if you want to provide some specific layout for the Arabic language and some generic layout for any other "right-to-left" language (like Persian or Hebrew) then you would have:

res/    layout/           main.xml  (Default layout)    layout-ar/          main.xml  (Specific layout for Arabic)    layout-ldrtl/          main.xml  (Any "right-to-left" language, except                  for Arabic, because the "ar" language qualifier                  has a higher precedence.)

Note: To enable right-to-left layout features for your app, you must setsupportsRtl to "true" and set targetSdkVersion to 17 or higher.

Added in API level 17.

smallestWidthsw<N>dp

Examples:
sw320dp
sw600dp
sw720dp
etc.

The fundamental size of a screen, as indicated by the shortest dimension of the available screen area. Specifically, the device's smallestWidth is the shortest of the screen's available height and width (you may also think of it as the "smallest possible width" for the screen). You can use this qualifier to ensure that, regardless of the screen's current orientation, your application has at least <N> dps of width available for its UI.

For example, if your layout requires that its smallest dimension of screen area be at least 600 dp at all times, then you can use this qualifer to create the layout resources, res/layout-sw600dp/. The system will use these resources only when the smallest dimension of available screen is at least 600dp, regardless of whether the 600dp side is the user-perceived height or width. The smallestWidth is a fixed screen size characteristic of the device; the device's smallestWidth does not change when the screen's orientation changes.

The smallestWidth of a device takes into account screen decorations and system UI. For example, if the device has some persistent UI elements on the screen that account for space along the axis of the smallestWidth, the system declares the smallestWidth to be smaller than the actual screen size, because those are screen pixels not available for your UI. Thus, the value you use should be the actual smallest dimension required by your layout (usually, this value is the "smallest width" that your layout supports, regardless of the screen's current orientation).

Some values you might use here for common screen sizes:

  • 320, for devices with screen configurations such as:
    • 240x320 ldpi (QVGA handset)
    • 320x480 mdpi (handset)
    • 480x800 hdpi (high-density handset)
  • 480, for screens such as 480x800 mdpi (tablet/handset).
  • 600, for screens such as 600x1024 mdpi (7" tablet).
  • 720, for screens such as 720x1280 mdpi (10" tablet).

When your application provides multiple resource directories with different values for the smallestWidth qualifier, the system uses the one closest to (without exceeding) the device's smallestWidth.

Added in API level 13.

Also see the android:requiresSmallestWidthDp attribute, which declares the minimum smallestWidth with which your application is compatible, and the smallestScreenWidthDp configuration field, which holds the device's smallestWidth value.

For more information about designing for different screens and using this qualifier, see the Supporting Multiple Screens developer guide.

Available widthw<N>dp

Examples:
w720dp
w1024dp
etc.

Specifies a minimum available screen width, in dp units at which the resource should be used—defined by the <N> value. This configuration value will change when the orientation changes between landscape and portrait to match the current actual width.

When your application provides multiple resource directories with different values for this configuration, the system uses the one closest to (without exceeding) the device's current screen width. The value here takes into account screen decorations, so if the device has some persistent UI elements on the left or right edge of the display, it uses a value for the width that is smaller than the real screen size, accounting for these UI elements and reducing the application's available space.

Added in API level 13.

Also see the screenWidthDp configuration field, which holds the current screen width.

For more information about designing for different screens and using this qualifier, see the Supporting Multiple Screens developer guide.

Available heighth<N>dp

Examples:
h720dp
h1024dp
etc.

Specifies a minimum available screen height, in "dp" units at which the resource should be used—defined by the <N> value. This configuration value will change when the orientation changes between landscape and portrait to match the current actual height.

When your application provides multiple resource directories with different values for this configuration, the system uses the one closest to (without exceeding) the device's current screen height. The value here takes into account screen decorations, so if the device has some persistent UI elements on the top or bottom edge of the display, it uses a value for the height that is smaller than the real screen size, accounting for these UI elements and reducing the application's available space. Screen decorations that are not fixed (such as a phone status bar that can be hidden when full screen) are not accounted for here, nor are window decorations like the title bar or action bar, so applications must be prepared to deal with a somewhat smaller space than they specify.

Added in API level 13.

Also see the screenHeightDp configuration field, which holds the current screen width.

For more information about designing for different screens and using this qualifier, see the Supporting Multiple Screens developer guide.

Screen sizesmall
normal
large
xlarge
  • small: Screens that are of similar size to a low-density QVGA screen. The minimum layout size for a small screen is approximately 320x426 dp units. Examples are QVGA low-density and VGA high density.
  • normal: Screens that are of similar size to a medium-density HVGA screen. The minimum layout size for a normal screen is approximately 320x470 dp units. Examples of such screens a WQVGA low-density, HVGA medium-density, WVGA high-density.
  • large: Screens that are of similar size to a medium-density VGA screen. The minimum layout size for a large screen is approximately 480x640 dp units. Examples are VGA and WVGA medium-density screens.
  • xlarge: Screens that are considerably larger than the traditional medium-density HVGA screen. The minimum layout size for an xlarge screen is approximately 720x960 dp units. 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.

Note: Using a size qualifier does not imply that the resources are onlyfor screens of that size. If you do not provide alternative resources with qualifiers that better match the current device configuration, the system may use whichever resources are the best match.

Caution: If all your resources use a size qualifier that is larger than the current screen, the system will not use them and your application will crash at runtime (for example, if all layout resources are tagged with the xlarge qualifier, but the device is a normal-size screen).

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 aspectlong
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.

Round screenround
notround
  • round: Round screens, such as a round wearable device
  • notround: Rectangular screens, such as phones or tablets

Added in API level 23.

Also see the isScreenRound() configuration method, which indicates whether the screen is round.

Screen orientationport
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.

UI modecar
desk
television
appliancewatch
  • car: Device is displaying in a car dock
  • desk: Device is displaying in a desk dock
  • television: Device is displaying on a television, providing a "ten foot" experience where its UI is on a large screen that the user is far away from, primarily oriented around DPAD or other non-pointer interaction
  • appliance: Device is serving as an appliance, with no display
  • watch: Device has a display and is worn on the wrist

Added in API level 8, television added in API 13, watch added in API 20.

For information about how your app can respond when the device is inserted into or removed from a dock, read Determining and Monitoring the Docking State and Type.

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

Night modenight
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. SeeHandling Runtime Changes for information about how this affects your application during runtime.

Screen pixel density (dpi)ldpi
mdpi
hdpi
xhdpi
xxhdpi
xxxhdpi
nodpi
tvdpi
  • 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
  • xxhdpi: Extra-extra-high-density screens; approximately 480dpi. Added in API Level 16
  • xxxhdpi: Extra-extra-extra-high-density uses (launcher icon only, see thenote in Supporting Multiple Screens); approximately 640dpi. Added in API Level 18
  • nodpi: This can be used for bitmap resources that you do not want to be scaled to match the device density.
  • tvdpi: Screens somewhere between mdpi and hdpi; approximately 213dpi. This is not considered a "primary" density group. It is mostly intended for televisions and most apps shouldn't need it—providing mdpi and hdpi resources is sufficient for most apps and the system will scale them as appropriate. This qualifier was introduced with API level 13.

There is a 3:4:6:8:12:16 scaling ratio between the six primary densities (ignoring the tvdpi density). So, a 9x9 bitmap in ldpi is 12x12 in mdpi, 18x18 in hdpi, 24x24 in xhdpi and so on.

If you decide that your image resources don't look good enough on a television or other certain devices and want to try tvdpi resources, the scaling factor is 1.33*mdpi. For example, a 100px x 100px image for mdpi screens should be 133px x 133px for tvdpi.

Note: Using a density qualifier does not imply that the resources areonly for screens of that density. If you do not provide alternative resources with qualifiers that better match the current device configuration, the system may use whichever resources are the best match.

See Supporting Multiple Screens for more information about how to handle different screen densities and how Android might scale your bitmaps to fit the current density.

Touchscreen typenotouch
finger
  • notouch: Device does not have a touchscreen.
  • finger: Device has a touchscreen that is intended to be used through direction interaction of the user's finger.

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

Keyboard availabilitykeysexposed
keyshidden
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 hiddenand 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 andkeyboardHidden, which indicate the visibility of a hardware keyboard and and the visibility of any kind of keyboard (including software), respectively.

Primary text input methodnokeys
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.

Navigation key availabilitynavexposed
navhidden
  • navexposed: Navigation keys are available to the user.
  • navhidden: Navigation keys are not available (such as behind a closed lid).

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 navigationHidden configuration field, which indicates whether navigation keys are hidden.

Primary non-touch navigation methodnonav
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.

Platform 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.

Note: Some configuration qualifiers have been added since Android 1.0, so not all versions of Android support all the qualifiers. Using a new qualifier implicitly adds the platform version qualifier so that older devices are sure to ignore it. For example, using a w600dp qualifier will automatically include the v13qualifier, because the available-width qualifier was new in API level 13. To avoid any issues, always include a set of default resources (a set of resources with no qualifiers). For more information, see the section aboutProviding the Best Device Compatibility with Resources.

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 inres/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="@drawable/icon_ca" />

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 theR.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/yellow</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 yourminSdkVersion is set to 4, and you qualify all of your drawable resources using night mode (night ornotnight, 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.

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 fromdrawable-en-port.

The system arrives at its decision for which resources to use with 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 theSupporting 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:
    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.

  5. 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/drawable-en-port/drawable-en-notouch-12key/

    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).

When selecting resources based on the screen size qualifiers, the system will use resources designed for a screen smaller than the current screen if there are no resources that better match (for example, a large-size screen will use normal-size screen resources if necessary). However, if the only available resources are largerthan the current screen, the system will not use them and your application will crash if no other resources match the device configuration (for example, if all layout resources are tagged with the xlarge qualifier, but the device is a normal-size screen).

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.

你应该总是外部化应用资源,如从你的代码的图像和字符串,这样就可以独立维护他们。你也应该为特定设备配置提供备用资源,通过特别命名的资源目录分组。在运行时,机器人使用基于当前配置相应的资源。例如,您可能想提供取决于屏幕大小或取决于语言设置不同的字符串不同的UI布局。

一旦外部化应用程序的资源,你可以使用在你的项目所产生的资源ID访问它们- [R类。如何在应用中使用的资源进行了讨论访问资源。本文将向您展示如何将你的资源在你的Android项目和具体的设备配置提供替代资源。

分组资源类型


你应该将每个类型的资源在您的项目的某个特定子目录 RES /目录下。例如,下面是一个简单的项目文件层次结构:

MyProject/     src/           MyActivity.java       res/         drawable/               graphic.png           layout/               main.xml             info.xml         mipmap/               icon.png         values/               strings.xml  

正如你可以看到在这个例子中,RES /目录中包含的所有资源(在子目录):图像资源,二布局资源的mipmap /为发射器的图标目录,和一个字符串资源文件。资源目录名称是重要的,在表1中描述。

注:有关使用的mipmap夹的详细信息,请参阅 管理项目概述。

表1.支持的项目中资源目录RES /目录下。

目录资源类型动画/定义XML文件的属性动画动画/定义XML文件补间动画。(物业动画也可以保存在此目录中,但动画/目录是首选的物业动画两种类型进行区分。)颜色/定义颜色的状态列表的XML文件。颜色状态列表资源绘制/

位图文件(巴纽.9.png.JPG.gif注意)或XML被编译成以下绘制资源亚型文件:

  • 位图文件
  • 九补丁(重相当大的位图)
  • 国家名单
  • 形状
  • 动画绘制资源
  • 其他可绘

绘制资源

的mipmap /可绘制文件不同的启动器图标密度。有关管理与发射器图标的详细信息的mipmap /文件夹,请参阅 管理项目概述布局/定义的用户接口布局的XML文件。参见布局资源菜单/定义应用程序菜单,如选项菜单,上下文菜单或子菜单的XML文件。菜单资源生的/

任意文件到原始形式保存。要使用原始打开这些资源 的InputStream,调用Resources.openRawResource()与资源ID,这是R.raw。文件名 ​​。

但是,如果您需要访问原来的文件名 ​​和文件的层次结构,你可以考虑在节约一些资源资产/目录(而不是RES /生/)。在文件中的资产/没有给出一个资源ID,所以你只能通过阅读它们AssetManager

值/

包含简单的值,如字符串,整数和颜色的XML文件。

而在其他的XML资源文件RES /子目录定义基于XML的文件名 ​​,一个单一的资源,在文件中值/目录描述多个资源。此目录中的文件时,每个孩子<资源>元素定义了一个单一的资源。例如,<字符串>元素创建一个 R.string资源和 <颜色>元素创建一个R.color 资源。

因为每个资源都与它自己的XML元素定义,您可以命名任何你想要的文件,并在一个文件放在不同的资源类型。然而,为了清晰起见,你可能希望将独特的资源类型在不同的文件。例如,这里有一些文件名约定你可以在这个目录下创建资源:

  • arrays.xml资源阵列(类型数组)。
  • colors.xml的颜色值
  • dimens.xml的尺寸值
  • strings.xml中的字符串值
  • styles.xml的风格

字符串资源, 样式资源,和 更多的资源类型

XML /可以在运行时通过调用任意读取XML文件Resources.getXML() 各种XML配置文件必须保存在这里,如一个可搜索的结构

注意:不要直接保存在里面的资源文件 RES /目录下,它会导致编译错误。

有关某些类型的资源的更多信息,请参见资源类型的文档。

您在表1中定义的子目录节省资源的“默认”的资源。也就是说,这些资源为应用程序定义默认的设计和内容。但是,不同类型的Andr​​oid设备可能会需要不同类型的资源。例如,如果一个设备具有大于普通屏幕,那么你应该提供利用多余的屏幕空间的优势,不同的布局资源。或者,如果设备有不同的语言设置,那么你就应该提供翻译在用户界面中的文本不同的字符串资源。要为不同的设备配置,提供这些不同的资源,您需要提供替代资源,除了默认的资源。

提供替代资源


图1的两个不同的设备,分别使用不同的布局的资源。

几乎每一个应用程序应该提供备用资源,以支持特定设备配置。例如,您应该包括不同屏幕密度和替代字符串资源为不同的语言替代绘图资源。在运行时,Android的检测当前的设备配置并加载相应的资源,为您的应用。

来指定一组资源的特定配置的替代方案:

  1. 创建一个新的目录RES /形式命名为<resources_name> - <config_qualifier> 
    • <resources_name>是相应的默认资源的目录名(在表1中定义)。
    • <限定符>是指定单个配置这些资源将被使用(在表2中所定义的)的名称。

    您可以附加一个以上的<预选赛>。分离每一个与破折号。

    注意:当附加多个限定符,必须将它们放置在它们被列于表2。如果预选赛排序错了相同的顺序,这些资源将被忽略。

  2. 这个新目录中保存相应的替代资源。资源文件必须被命名为完全一样的默认资源文件。

例如,这里有一些默认的和替代性资源:

RES /     绘制/            的icon.png         background.png         绘制,华电国际/           的icon.png         background.png  

华电国际限定符表示该目录中的资源是具有高密度屏幕的设备。在每一个这些可拉伸目录的图像的尺寸对于特定屏密度,但是文件名 ​​是完全一样的。这样一来,您使用引用的资源ID 的icon.pngbackground.png形象是永远不变的,而Android的每个选择最当前的设备相匹配,通过设备的配置信息与在预选赛中比较资源的版本资源目录名称。

Android支持多种配置限定符,您可以通过每个限定符以破折号分隔添加多个预选赛一个目录名。表2列出了有效的配置预选赛中的优先顺序,如果你使用多个限定符的资源目录,则必须将它们添加到它们在表中列出的顺序的目录名。

表2.配置预选赛名。

组态限定词值描述MCC和MNC例如:mcc310mcc310-mnc004mcc208-mnc00等。 



从该装置中的SIM卡的移动国家代码(MCC),任选地随后移动网络代码(MNC)。例如,mcc310是美国任何载体上, mcc310-mnc004是美国的Verizon和mcc208-mnc00是法国橙色。

如果设备使用的无线连接(GSM电话),MCC和MNC值来自SIM卡。

您也可以只使用MCC(例如,在您的应用程序特定国家的法律资源)。如果你需要指定基于语言只,然后用 语言和区域预选赛,而不是(下面讨论)。如果您决定使用MCC和MNC预选赛上,你应该小心操作和测试,它按预期工作。

另请参见配置字段MCCMNC,这表明目前的移动国家代码和移动网络代码分别。

语言和区域例如:EN FREN-RUS FR-RFRFR-RCA 等。 





语言是由两个字母定义的ISO 639-1语言代码,后面可以跟一个两个字母的ISO 3166-1-α-2区代码(小写“开头- [R ”)。

该代码是区分大小写; ř前缀用于区分区域部分。你不能仅靠指定的区域。

这可以如果用户在系统设置更改他或她的语言应用程序的生命周期内发生改变。请参阅处理运行时更改的信息,这将如何运行时影响应用程序。

本地化的完整指南本地化用于其他语言的应用程序。

另请参见区域配置领域,这表明当前的语言环境。

布局方向ldrtl 
ldltr

您的应用程序。布局方向ldrtl意思是“布局方向从右至左”。 ldltr意思是“布局方向左到右”,这是默认内含价值。

这可以适用于任何资源,如布局,图形或值。

例如,如果你想为阿拉伯语一些特定的布局和一些通用布局的任何其他“从右至左”语言(如波斯语或希伯来语),那么你就必须:

RES /     布局/            main.xml中  (默认布局)    布局-AR /           main.xml中  (具体布局阿拉伯语)    布局ldrtl /           main.xml中  (任何“从右至左”语言,除了                  阿拉伯语,因为“AR “语言限定                  具有更高的优先级。)

注:为了使您的应用程序从右到左的布局功能,您必须设置supportsRtl“真”,并设置targetSdkVersion为17或更高。

在API级别17。

最小宽度SW <N> DP

例子:sw320dpsw600dpsw720dp 等。 



屏幕的基本大小,可用屏幕区域的最短尺寸如图所示。具体而言,该器件的最小宽度是最短的屏幕的可用高度和宽度(你也可以认为它是“最小宽度可能”为屏幕)的。你可以使用这个限定词,以确保,无论画面当前的方向,你的应用程序至少<N>供其UI宽度DPS。

例如,如果你的布局要求,其最小的屏幕面积的大小至少为600 DP在任何时候,那么你可以使用这个限定符创建布局资源,RES /布局sw600dp /。只有当可用屏幕的最小尺寸至少为600 dp,无论600dp的一侧是否是用户感知的高度或宽度,系统将使用这些资源。的最小宽度是该装置的一个固定屏幕大小特性; 当屏幕的方向改变了设备的smallestWidth不会改变

设备的最小宽度考虑到屏幕装饰和系统界面。例如,如果设备具有占沿smallestWidth轴线空间在屏幕上一些持久UI元素,该系统的smallestWidth为比实际的屏幕尺寸小,因为这些是可提供的UI画面的像素。因此,您使用应该是实际的最小尺寸值由布局要求(通常情况下,这个值是你的布局支持,无论画面的当前方位的“最小宽度”)。

有些值你可以使用这里常见的屏幕尺寸:

  • 320,对于屏幕配置,如设备:
    • 240×320 LDPI(QVGA手机)
    • MDPI小320x480(手机)
    • 为480x800华电国际(高密度手机)
  • 480,对于屏幕,如480×800 MDPI(平板电脑/手机)。
  • 600,对于屏幕如600x1024 MDPI(7“平板电脑)。
  • 720,对于屏幕如720x1280 MDPI(10“平板电脑)。

当应用程序提供的最小宽度限定不同值的多个资源目录,该系统采用一个最接近于(不超过)设备的smallestWidth。

在API级别13。

也看到了安卓requiresSmallestWidthDp属性,它宣布最低最小宽度与您的应用程序是兼容的,并且smallestScreenWidthDp配置字段,用于存放设备的smallestWidth价值。

有关设计为不同的屏幕,并使用此限定符的更多信息,请参阅支持多种屏幕开发人员指南。

可用宽度是W <N> DP

例子:w720dpw1024dp 等。 


指定的最小可用屏幕宽度,以DP单位在该资源应该被用来定义<N>的值。当方向横向和纵向之间切换到当前的实际宽度相符,这个设定值将发生变化。

当你的应用程序提供了此配置的不同值的多个资源目录,该系统采用一个最接近于(不超过)设备的当前屏幕的宽度。这里的值考虑到屏幕的装饰品,因此,如果该装置具有在显示器的左边缘或右边缘的一些持久性UI元素,它使用了比所述真实画面尺寸小的宽度的值,占这些UI元素和还原应用程序的可用空间。

在API级别13。

另请参见screenWidthDp 配置字段,它保存了当前屏幕的宽度。

有关设计为不同的屏幕,并使用此限定符的更多信息,请参阅支持多种屏幕开发人员指南。

可用高度^ h <N> DP

例子:h720dph1024dp 等。 


指定的最小可用屏幕的高度,在该资源应该由所使用的定义“DP”单位<N>的值。当方向横向和纵向之间切换,以匹配当前的实际高度,这个设定值将发生变化。

当你的应用程序提供了此配置的不同值的多个资源目录,该系统采用一个最接近于(不超过)设备的当前屏幕的高度。这里的值考虑到屏幕的装饰品,因此,如果该装置具有在显示器的顶部或底部边缘的一些持久性UI元素,它使用了比所述真实画面尺寸小的高度的值,占这些UI元素和还原应用程序的可用空间。这是不固定的(例如,当全屏可以隐藏在手机状态栏)的屏幕装饰品占在这里,也不是窗口装饰之类的标题栏或操作栏,因此应用程序必须准备应对稍小空间比他们指定。

在API级别13。

另请参见screenHeightDp 配置字段,它保存了当前屏幕的宽度。

有关设计为不同的屏幕,并使用此限定符的更多信息,请参阅支持多种屏幕开发人员指南。

屏幕尺寸
正常

XLARGE
  • :屏幕是相似大小的低密度QVGA屏幕。对于小屏幕的最小布局尺寸大约为320x426 dp单位。例子是QVGA低密度和VGA高密度。
  • 正常:屏幕是相似大小的中密度HVGA屏幕。对于普通屏幕的最小布局尺寸大约为320x470 dp单位。一个WQVGA低密度,HVGA中密度,WVGA高密度这样的屏幕的例子。
  • :屏幕是相似大小的中密度VGA屏幕。对于大屏幕的最小布局尺寸约为480×640 dp单位。例子有VGA和WVGA中密度屏幕。
  • XLARGE:是比传统的中密度HVGA屏幕大得多的屏幕。对于XLARGE屏幕的最小布局尺寸大约为720x960 dp单位。在大多数情况下,具有超大屏幕的设备将太大装在口袋里携带,最有可能是平板电脑式的设备。在API 9级。

注意:使用尺寸限定符并不意味着资源是对于该尺寸的屏幕。如果你不提供备用资源与更好地匹配当前设备配置预选赛中,该系统可以使用的任何资源是最佳匹配

注意:如果所有的资源使用大小限定符是更大比当前屏幕,系统将不会使用它们,您的应用程序在运行时崩溃(例如,如果所有的布局资源都标有XLARGE预选赛,但该设备一个正常大小的屏幕)。

在API级别4。

支持多种屏幕以获取更多信息。

另请参见屏幕布置配置字段,表示屏幕是小的,正常的,或大。

屏幕宽高比
notlong
  • :龙屏风,如WQVGA,WVGA,FWVGA
  • notlong:不长的屏幕,比如QVGA,HVGA和VGA

在API级别4。

这纯粹是基于屏幕的纵横比(“长”屏幕更宽)。这是不相关的屏幕方向。

另请参见屏幕布置配置字段,表示屏幕是否长。

圆筛
notround
  • :圆形的屏幕,如圆穿戴设备
  • notround:矩形屏幕,如手机或平板电脑

在API级别23。

另请参阅isScreenRound()的配置方法,它指示屏幕是否是圆的。

屏幕方向
  • 端口:设备是纵向(垂直)
  • 土地:设备处于横向(水平)

这可以当用户旋转屏幕应用程序的生命周期内发生改变。请参阅处理运行时更改了有关如何在运行时这会影响您的应用程序的信息。

另请参见方向配置领域,这表明当前设备的方向。

UI模式

电视家电手表
 
  • 汽车:设备在汽车码头显示
  • :设备在桌子显示坞
  • 电视:设备显示在电视上,提供了“十英尺”体验,其用户界面是在大屏幕上,用户远离,主要围绕DPAD或其他非指针面向互动
  • 家电:设备作为一个设备,不带显示器
  • 观看:设备具有显示器,并戴在手腕上

在API级别8,电视13 API补充道,20 API手表说。

有关时,该设备被插入或删除,从码头您的应用程序可以如何回应的信息,请参阅确定和监测的对接状态和类型

这可以在用户将器件置于基座应用程序的生命周期内发生改变。您可以启用或禁用某些使用这些模式的UiModeManager请参阅处理运行时更改了有关如何在运行时这会影响您的应用程序的信息。

夜间模式晚上
notnight
  • 夜间:夜间
  • notnight:天时间

在API级别8。

这可如果夜间模式在自动模式(默认),在这种情况下,根据一天中的时间模式改变离开你的应用程序的生命周期内发生改变。您可以启用或禁用使用此模式UiModeManager请参阅处理运行时更改了有关如何在运行时这会影响您的应用程序的信息。

屏幕像素密度(DPI)LDPI 
MDPI 
华电国际
xhdpi 
xxhdpi 
xxxhdpi 
nodpi 
tvdpi
  • LDPI:低密度的屏幕; 约120DPI。
  • MDPI:中密度(传统HVGA)的屏幕; 约160dpi。
  • 华电国际:高密度屏幕; 约240dpi。
  • xhdpi:特高密度屏幕; 大约320dpi,在API级别8
  • xxhdpi:特超高密度屏幕; 大约480dpi,在API级别16
  • xxxhdpi:特超超高密度的用途(只启动器图标,看到 音符 中支持多种屏幕); 大约640dpi,在API等级18
  • nodpi:这可以用于你不希望被缩放到器件密度相匹配的位图的资源。
  • tvdpi:MDPI和hdpi之间的屏幕; 约213dpi。这不被视为一个“主”密度组。它主要用于电视和大多数应用程序并不需要它,提供MDPI和华电国际的资源足以满足大多数应用程序,系统将扩展他们适当的。此限定符与API级别13引入的。

有一个3:4:6:8:12:的六个主密度(忽略tvdpi密度)之间16缩放比率。所以,在LDPI一个9x9的位图是在MDPI 12×12,18×18在hdpi的,24×24在xhdpi等。

如果您认为您的图片资源不看不够好电视或其它某些设备上,并想尝试tvdpi资源,在缩放倍率是1.33 * MDPI。例如,对于mdpi屏幕的100像素点¯x100px的形象应该是133px点¯x133px的tvdpi。

注意:使用密度限定符并不意味着资源是对于密度的屏幕。如果你不提供备用资源与更好地匹配当前设备配置预选赛中,该系统可以使用的任何资源是最佳匹配

支持多种屏幕有关如何处理不同的屏幕密度,以及如何Android的可能扩展你的位图,以适应电流密度的更多信息。

触摸屏类型notouch 
手指
  • notouch:设备不具有触摸屏。
  • 手指:设备具有旨在通过用户的手指的方向相互作用中使用的触摸屏。

还看到触摸屏配置字段,其指示触摸屏的设备的类型。

键盘的可用性keysexposed 
keyshidden 
keyssoft
  • keysexposed:装置有可用的一个键盘。如果该装置具有使一个软件键盘(这是可能的),即使当硬件键盘这可用于 暴露给用户,即使该设备没有硬件键盘。如果没有提供软件键盘,或者它关闭,那么这是仅当一个硬件键盘露出使用。
  • keyshidden:设备有可用的硬件键盘,但它是隐藏设备不启用的软件键盘。
  • keyssoft:设备启用了软键盘,无论是可见或不可见。

如果提供keysexposed资源,但不keyssoft 资源,该系统采用了keysexposed资源不管键盘是否是可见的,只要该系统启用的软件键盘。

这可以,如果用户打开一个硬件键盘应用程序的生命周期内发生改变。请参阅处理运行时更改了有关如何在运行时这会影响您的应用程序的信息。

另请参见配置字段hardKeyboardHiddenkeyboardHidden,这表明一个硬件键盘的知名度和任何类型的键盘分别为(包括软件)的知名度。

主要文本输入法nokeys 
QWERTY 
12key
  • nokeys:设备具有文字输入任何硬件按键。
  • QWERTY:装置有一个硬件QWERTY键盘,无论是对用户或不可见的。
  • 12key:装置有一个硬件12键键盘,无论是对用户或不可见的。

还看到键盘配置字段,其指示提供的主文本输入方法。

导航键的可用性navexposed 
navhidden
  • navexposed:导航键是提供给用户。
  • navhidden:导航键是不可用(如封闭的盖的后面)。

这可以如果用户发现导航键应用程序的生命周期内发生改变。请参阅处理运行时更改了有关如何在运行时这会影响您的应用程序的信息。

另请参见navigationHidden配置字段,它指示导航键是否被隐藏。

主要非触摸导航方法nonav 
DPAD 
轨迹球
  • nonav:设备具有比使用触摸屏之外,没有其他的导航设备。
  • DPAD:设备具有导航定向垫(D-PAD)。
  • 轨迹球:装置有用于导航轨迹球。
  • :设备具有导航(罕见)定向轮(S)。

另请参见导航配置字段,它指示导航方法的类型可用。

平台版本(API等级)例如:V3 V4V7 等。



API级别设备支持。例如,V1的API等级1(与Android 1.0或更高版本的设备)和V4的API等级4(与Android 1.6或更高版本的设备)。看到Android的API级别的文件有关这些值的更多信息。

注:由于Android 1.0的一些配置预选赛已经添加,所以并不是Android的支持所有的预选赛所有版本。使用新的限定词隐含增加了平台版本预选赛使旧设备肯定会忽略它。例如,使用w600dp预选赛将自动包括V13预选赛上,因为可用的宽度限定在API级别13新为了避免任何问题,总是包括一组默认的资源(带一组资源的限定符)。欲了解更多信息,请参阅有关章节利用资源提供最佳的设备兼容性。

预选赛名称规则

以下是关于使用配置限定符一些规则:

  • 您可以为一组资源,短横线分开指定多个限定符。例如,绘制-ZH-RUS-地适用于横向美国英语设备。
  • 限定符必须是在列出的顺序表2,例如:
    • 错误:绘制-HDPI端口/
    • 正确:绘制口,华电国际/
  • 替代资源目录不能嵌套。例如,你不能有 RES /绘制/绘恩/
  • 值不区分大小写。资源编译器处理,以避免不区分大小写的文件系统的问题之前,目录名转换为小写。名称中的任何资本仅仅是受益可读性。
  • 支持每个词类型只有一个值。例如,如果您要使用西班牙和法国同绘文件,你不能有一个名为 绘-RES-RFR /。相反,你需要两个资源目录,如 绘制-RES /绘制-RFR /,其中包含相应的文件。不过,你不需要实际复制在这两个位置相同的文件。相反,你可以创建一个别名的资源。请参阅创建别名资源下文。

在保存替代资源与这些限定词命名的目录,Android的自动根据当前设备配置在您的应用程序适用的资源。每次请求资源时,机器人检查包含所请求的资源的文件替代资源目录,然后找到最佳匹配的资源(以下讨论)。如果有匹配特定的设备配置,没有替代资源,然后Android使用相应的默认资源(不包括一个配置限定符特定资源类型的一组资源)。

创建别名资源

当你有,你想使用一个以上的设备配置(但不希望提供作为默认的资源)的资源,你不需要把同一资源在多个替代资源目录。相反,你可以(在某些情况下)创建充当保存到默认的资源目录的资源的别名替代的资源。

注:并非所有的资源提供,通过它可以创建一个别名到另一个资源的机制。特别是,动画,菜单,原料,以及其他未说明的资源,在XML /目录中不提供此功能。

例如,假设你有一个应用程序图标,的icon.png,并且需要不同地区的独特之处版本。但是,有两个语言环境,英语,加拿大和法国,加拿大,必须使用相同的版本。你可能会认为你需要相同的图像复制到资源目录英语,加拿大和法国,加拿大,但事实并非如此。相反,你可以保存的用于两个作为图像icon_ca.png(比其他任何名称的icon.png),并把它放在默认的RES /绘制/目录下。然后创建一个icon.xml文件RES /绘-ZH-RCA /RES /绘-FR-RCA /是指icon_ca.png 使用资源<位>元素。这允许你只存储一个版本的PNG文件,并指向它两个小的XML文件。(示例XML文件如下所示。)

可绘制

创建别名到现有的绘制,使用<位图>元素。例如:

<?xml的version = "1.0" encoding = "utf-8" ?> <bitmap  xmlns:android = "http://schemas.android.com/apk/res/android"     android:src = "@drawable/icon_ca"  />

如果您将此文件保存为icon.xml(,在替代资源目录,如 RES /绘-EN-RCA /),它被编译成一种资源,可以作为参考R.drawable.icon,但实际上是一个别名对于R.drawable.icon_ca资源(保存在RES /绘制/)。

布局

创建别名到现有的布局,使用<包括> 元素,包裹在一个<合并>。例如:

<?XML版本= “1.0” 编码= “UTF-8” ?> <合并>     <包括 布局= “@布局/ main_ltr” /> </合并>

如果您将此文件保存为main.xml中,它被编译成可以作为参考的资源R.layout.main,但实际上是对一个别名R.layout.main_ltr 资源。

字符串等简单值

创建别名到现有的字符串,只需使用所需的字符串资源ID作为新的字符串值。例如:

<?xml的version = "1.0" encoding = "utf-8" ?> <resources>     <string  name = "hello" > Hello </string>     <string  name = "hi" > @string/hello </string> </resources>

R.string.hi现在的资源是为一个别名R.string.hello

其他简单的值相同的方式工作。例如,一颜色:

<?xml的version = "1.0" encoding = "utf-8" ?> <resources>     <color  name = "yellow" > #f00 </color>     <color  name = "highlight" > @color/yellow </color> </resources>

利用资源提供最佳的设备兼容性


为了让您的应用程序支持多个设备配置,这是非常重要的,你永远是您的应用程序使用的每个类型的资源提供默认的资源。

例如,如果你的应用程序支持多种语言,始终包括值/目录(你的字符串保存)没有一个语言和区域预选赛如果你不是把你所有的字符串文件具有语言和区域预选赛目录,那么当设置为你的弦不支持的语言的设备上运行应用程序会崩溃。但是,只要你提

供默认 值/资源,那么你的应用程序将正常运行(即使用户不理解的语言,它比崩溃更好)。

同样,如果你提供了基于屏幕的方向不同的布局资源,你应该选择一个方向作为默认。例如,而不是提供布局资源布局的土地/景观和布局端口/肖像,留下一个作为默认,如 布局/景观和布局端口/肖像。

提供了默认的资源不仅是因为您的应用程序可能会在配置运行,你没有预料到,也因为Android的新版本有时会添加旧版本不支持配置预选赛是非常重要的。如果使用新的资源预选赛,但保持与旧版本的Android的代码兼容性,那么当Android的旧版本,运行应用程序,它会崩溃,如果你不提供默认的资源,因为它不能使用新命名的资源预选赛。例如,如果你的minSdkVersion设置为4,和您符合所有使用绘图资源的夜间模式(夜间notnight,这是在API级别8加入),然后是API级别4的设备无法访问您的绘图资源,并会崩溃。在这种情况下,你可能想notnight成为默认的资源,所以你应该排除限定让你的绘图资源是不是可绘制/绘制夜/

因此,为了提供最好的设备兼容性,永远为您的应用程序需要进行适当的资源提供默认的资源。然后创建使用设定限定特定设备配置替代资源。

有一个例外:如果你的应用程序的minSdkVersion是大于或等于4,你不会需要预设绘制资源,当您提供替代绘图资源与屏幕密度预选赛。即使没有默认的绘制资源,机器人可以找到替代的屏幕密度之间的最佳匹配,并缩放位图是必要的。但是,对于所有类型的设备提供最佳体验,您应该为所有三种类型的密度提供备用可绘制。

Android如何寻找最匹配的资源


当您请求为您提供替代的资源,Android的选择了替代资源在运行时使用,根据当前的设备配置。为了演示的Andr​​oid如何选择一个替代资源,假设以下绘制资源目录分别包含不同版本的同一图片:

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

并且假设以下是设备配置:

区域设置= EN-GB 
屏幕方向= 端口 
屏幕像素密度= 华电国际 
触摸屏类型= notouch 
主要文本输入法= 12key

通过设备配置比较可用的替代资源,Android的选择来自可绘制可绘制烯端口

该系统到达其决定与以下逻辑要使用的资源:

图2.流程图的Android如何寻找最佳匹配的资源。

  1. 消除矛盾的设备配置资源文件。

    绘制-FR-RCA /目录中被淘汰,因为它违背了EN-GB语言环境。

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

    例外:屏幕的像素密度是一个限定符不会由于一个矛盾消除。即使该装置的屏幕密度HDPI,抽拉口-LDPI /不消除,因为每个屏幕的密度被认为是在这一点上的匹配。更多信息将在提供支持多种屏幕文件。

  2. 匹克在列表((下)最高优先级预选赛表2)。(开始与MCC,然后向下移动。)
  3. 做任何资源目录包括这个限定词?
    • 如果没有,回到步骤2,并期待在接下来的预选赛。(在这个例子中,答案是“否”,直到达到语言限定符)。
    • 如果是,继续执行步骤4。
  4. 消除资源目录不包括这个限定词。在这个例子中,系统消除所有不包括一个语言限定符的目录:
    drawable/ drawable-en/ drawable-en-port/ drawable-en-notouch-12key/ drawable-port-ldpi/ drawable-port-notouch-12key/

    例外:如果有问题的预选赛是屏幕像素密度,Android的选择,该设备屏幕密度最匹配的选项。一般情况下,Android的更喜欢较大的原始图像缩小到扩大规模较小的原始图像。见支持多种屏幕。

  5. 返回并重复步骤2,3,和4,直到只有一个目录仍然存在。在这个例子中,屏幕取向是下一个限定符其中有任何匹配。所以,没有指定屏幕方向的资源被淘汰:
    绘制恩/ 绘烯端口/ 绘烯notouch-12key /

    其余的目录是绘制烯端口

虽然这个过程是针对每个被请求的资源执行,该系统进一步优化某些方面。一个这样的优化是,一旦设备配置是已知的,它可能会消除,可以从未匹配的替代资源。例如,如果配置的语言是英语(“EN”),那么,有一个语言限定符设置为英语以外的其他任何资源目录从不包括在资源检查的池(尽管一个资源目录没有语言限定符仍包括在内)。

当基于屏幕尺寸预选赛选择资源时,系统将使用专为比当前屏幕较小的屏幕资源,如果没有资源,更好地匹配(例如,大尺寸屏幕将在必要时使用标准尺寸屏幕的资源)。然而,如果唯一可用的资源是较大的比当前屏幕,系统将使用它们,如果没有其他的资源相匹配的设备配置(例如,如果所有的布局资源的标签与你的应用将崩溃XLARGE限定符,但设备是一个正常大小的屏幕)。

注:优先限定符(在表2)比完全设备匹配限定符的数目更重要。例如,在上面的步骤4中,列表中的最后的选择包括恰好在设备(取向,触摸屏类型,并输入方式)匹配,而3限定符抽拉烯只有一个匹配参数(语言)。然而,语言比这些限定词的优先级高,所以 绘制端口-notouch-12key出来了。

要了解更多有关如何在你的应用程序中使用资源,继续访问资源。


0 0
原创粉丝点击