【Android API Guides 簡譯(二)】App Resourses--Providing Resources

本文接引上文,主要解釋如何在你的工程裏組織資源和向不同的設備環境提供特有的資源。

一、分組資源種類

我們把所有資源分門別類的放在/res下的不同文件夾下,而且/res下的每一個文件夾的名稱非常重要,代表不同的含義,如下表所示:

Table 1. Resource directories supported  inside  project

res/ directory.


Directory Resource Type
animator/ XML files that define propertyanimations.
anim/ XML files that define tweenanimations. (Property animations can also be saved in this directory, buttheanimator/ directory is preferred for property animations to distinguish between the twotypes.)
color/ XML files that define a state list of colors. See ColorState List Resource
drawable/

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

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

See Drawable Resources.

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

Arbitrary files to save in their raw form. To open these resources with a rawInputStream, callResources.openRawResource() with the resource ID, which isR.raw.filename.

However, if you need access to original file names and file hierarchy, you might considersaving some resources in theassets/ directory (instead ofres/raw/). Files in assets/ are not given aresource ID, so you can read them only usingAssetManager.

values/

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

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

Because each resource is defined with its own XML element, you can name the filewhatever you want and place different resource types in one file. However, for clarity, you mightwant to place unique resource types in different files. For example, here are some filenameconventions 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 filesmust be saved here, such as asearchable configuration.

注意:不要直接將資源文件保存在/res目錄下,這會造成構建錯誤。

你保存在表一上的子目錄下的資源被認定爲默認資源,也就是說這些資源被認定爲你手機應用的默認設計和默認內容。那麼如何爲不同的設備或者不同的語言環境提供特定的資源?

二、提供特定的資源

提供特定資源使其在運行過程中,爲你的應用探測當前的環境,提供對應的資源。

我們通過以下來分辨和劃分特定的資源:

1、以<resources_name>-<config_qualifier>的命名形式在res文件夾下創建一個新的目錄。

resources_name:對應相應的默認資源的目錄名

config_qualifier:對應特殊資源的限定詞,限定詞必須是規定在表2的範圍內。

你可以爲一個目錄添加一個以上的限定詞,同過"-"隔開。

注意:當一個文件夾規定多個限定詞時,他們必須按照表二的順序排列,否則工程會忽略這個資源目錄。

2、向相應的特殊子目錄分配相應的資源,分配的資源名要和默認文件夾下的對應資源名一致。

比如:

hdpi”表明在這個文件夾裏的資源適合高密度的屏幕。在不同文件夾裏的資源適合不同的屏幕密度,但它們的文件名相同。通過這種方式,你在代碼中使用的Resourse ID相同,但安卓機會通過比較當前手機配置和限定詞,來選擇最適合手機配置的資源。

以下是各種限定詞的使用規則和排列順序:

Table 2. Configuration qualifiernames.


Configuration 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,mcc310 is U.S. on any carrier,mcc310-mnc004 is U.S. on Verizon, andmcc208-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 legalresources in your application). If you need to specify based on the language only, then use thelanguage and region qualifier instead (discussed next). If you decide to use the MCC andMNC 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 codeand mobile network code, respectively.

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 "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 lifeof your application if the user changes his or her language in the system settings. SeeHandling Runtime Changes for information abouthow this can affect your application during runtime.

See Localization for a complete guide to localizingyour application for other languages.

Also see the locale configuration field, whichindicates the current locale.

Layout Direction ldrtl
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.

smallestWidth sw<N>dp

Examples:
sw320dp
sw600dp
sw720dp
etc.

The fundamental size of a screen, as indicated by the shortest dimension of the availablescreen area. Specifically, the device's smallestWidth is the shortest of the screen's availableheight and width (you may also think of it as the "smallest possible width" for the screen). You canuse this qualifier to ensure that, regardless of the screen's current orientation, yourapplication 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 atleast 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 ofavailable screen is at least 600dp, regardless of whether the 600dp side is the user-perceivedheight or width. The smallestWidth is a fixed screen size characteristic of the device;thedevice's smallestWidth does not change when the screen's orientation changes.

The smallestWidth of a device takes into account screen decorations and system UI. Forexample, if the device has some persistent UI elements on the screen that account for space alongthe axis of the smallestWidth, the system declares the smallestWidth to be smaller than the actualscreen size, because those are screen pixels not available for your UI. Thus, the value you useshould be the actual smallest dimensionrequired 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) thedevice's smallestWidth.

Added in API level 13.

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

For more information about designing for different screens and using thisqualifier, see theSupportingMultiple Screens developer guide.

Available width w<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 thisqualifier, see theSupportingMultiple Screens developer guide.

Available height h<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) arenot 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 thisqualifier, see theSupportingMultiple Screens developer guide.

Screen size small
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 theresources areonly for screens of that size. If you do not provide alternativeresources with qualifiers that better match the current device configuration, the system may usewhichever resources are thebest match.

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

Added in API level 4.

See Supporting MultipleScreens for more information.

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

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

Added in API level 4.

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

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

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

This can change during the life of your application if the user rotates thescreen. SeeHandling Runtime Changes for information abouthow this affects your application during runtime.

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

UI mode car
desk
television
appliance watch
  • 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, readDeterminingand Monitoring the Docking State and Type.

This can change during the life of your application if the user places the device in adock. You can enable or disable some of these modes usingUiModeManager. SeeHandling Runtime Changes forinformation about how this affects your application during runtime.

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

Added in API level 8.

This can change during the life of your application if night mode is left inauto mode (default), in which case the mode changes based on the time of day. You can enableor disable this mode usingUiModeManager. SeeHandling Runtime Changes for information about how this affects yourapplication 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; approximately160dpi.
  • hdpi: High-density screens; approximately 240dpi.
  • xhdpi: Extra-high-density screens; approximately 320dpi. Added in APILevel 8
  • xxhdpi: Extra-extra-high-density screens; approximately 480dpi. Added in APILevel 16
  • xxxhdpi: Extra-extra-extra-high-density uses (launcher icon only, see thenote inSupporting Multiple Screens); approximately 640dpi. Added in APILevel 18
  • nodpi: This can be used for bitmap resources that you do not want to be scaledto match the device density.
  • tvdpi: Screens somewhere between mdpi and hdpi; approximately 213dpi. This isnot considered a "primary" density group. It is mostly intended for televisions and mostapps shouldn't need it—providing mdpi and hdpi resources is sufficient for most apps andthe 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 thetvdpi 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 orother certain devices and want to try tvdpi resources, the scaling factor is 1.33*mdpi. Forexample, a 100px x 100px image for mdpi screens should be 133px x 133px for tvdpi.

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

See Supporting MultipleScreens for more information about how to handle different screen densities and how Androidmight scale your bitmaps to fit the current density.

Touchscreen type notouch
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 availability keysexposed
keyshidden
keyssoft
  • keysexposed: Device has a keyboard available. If the device has asoftware keyboard enabled (which is likely), this may be used even when the hardware keyboard isnot exposed to the user, even if the device has no hardware keyboard. If no softwarekeyboard is provided or it's disabled, then this is only used when a hardware keyboard isexposed.
  • keyshidden: Device has a hardware keyboard available but it ishiddenand the device doesnot have a software keyboard enabled.
  • keyssoft: Device has a software keyboard enabled, whether it'svisible or not.

If you provide keysexposed resources, but not keyssoftresources, the system uses thekeysexposed resources regardless of whether akeyboard 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 hardwarekeyboard. SeeHandling Runtime Changes for information about howthis affects your application during runtime.

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

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

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

Platform Version (API level) Examples:
v3
v4
v7
etc.

The API level supported by the device. For example, v1 for API level1 (devices with Android 1.0 or higher) andv4 for API level 4 (devices with Android1.6 or higher). See theAndroid API levels document for more informationabout these values.


限定詞使用規則

以下是使用限定詞的幾個規則:

1、你可以用多個限定詞來區分一種特殊的資源,限定詞之間用“-”隔開。

2、限定詞必須按表二的順序排列。例如:

正確:drawable-port-hdpi/

錯誤:drawable-hdpi-port/

3、特定的資源目錄不能被嵌套。例如:

不存在res/drawable/drawable-en/

4、值是區分大小寫的。但是爲了避免在大小寫系統上出現錯誤,系統在處理數據前會先把所有大寫轉化成小寫字母,所以任何名字中的大寫字母只是爲了提高可讀性。

5、同類型的限定詞同時只能有一個在資源名上出現。比如你想要爲西班牙和法國的手機app用同一個圖片,你不可以用drawable-rES-rFR/。你只能用兩個內容相同的目錄drawable-rES/drawable-rFR/。但你確實不需要在相同的位置複製同一個文件,只需要創建一個別名資源。具體可見下部分創建別名資源。

在通過限定詞創建了特定資源的目錄後,Android會自動根據當前環境,提供最合適的資源。每次資源被請求使用,Android會自動檢查,尋找最合適的資源,如果不存在最合適的資源,系統會使用默認資源。

創建別名資源

當你希望一個特定資源用在不同的特定環境時(指的不是默認資源),你不需要在兩個不同的特定資源目錄下存放相同的資源,你只需要將特定資源放在默認文件夾裏,然後在麼個特定資源目錄裏,加入指向該資源的XML文件。

例如:

icon_ca.png 特殊資源使用在英語和法語環境下,我們把icon_ca.png 放在res/drawable/ 目錄下,再在res/drawable-en-rCA/res/drawable-fr-rCA/下放置icon.xml

icon.xml只允許我們創建一種版本的PNG文件。icon.xml具體形式見下文。

注意:不是所有的資源都可以使用別名資源,通常animation, menu, raw,和其他在/xml文件夾裏的資源沒有這個現象。

Drawable

<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/icon_ca" />
如果你在res/drawable-en-rCA/ 中保存的是icon.xml,R文件內顯示的是R.drawable.icon,實際上它就是存放在默認目錄下的R.drawable.icon_ca 資源的映像。

Layout

<?xml version="1.0" encoding="utf-8"?>
<merge>
    <include layout="@layout/main_ltr"/>
</merge>
具體同上,注意標籤名的不同。

Strings and other simple values

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

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

現在,R.string.hi資源就是R.string.hello資源的映射。


三、提供最好的資源兼容性。

爲了保證你的app能夠在多個設備上運行,必須在默認資源環境中設置資源。否則如果你只在各種含有限定詞的目錄下放置資源,一旦運行在一個app不支持的語言環境下,就會崩潰。

放置默認資源的原因如此重要並不只是因爲你的應用會遇到你沒有想到的環境,事實上更多是因爲有時新版本增加的限定詞,舊版本無法支持。即當你在未設置默認資源時使用一個新的限定詞,而設備卻保持原有的編碼兼容性,於是設備無法識別你增加的限定詞,在運行時就會出現崩潰。比如我們設置一個工程的最低SDK爲4,那麼在我們使用夜間模式下的圖片時,系統就會因爲無法找到drawable-night/內的圖片而崩潰(夜間模式的限定詞在SDK8纔開始使用)。此時我們最好就是在默認資源和drawable-night/都設置相應的圖片。

所以一般我們先將所有可能用到的圖片設置在默認資源裏,再相應的添加特定資源。

這個規則的唯一例外是在SDK4版本以上的版本,不需要爲屏幕密度相關的限定詞在默認目錄裏添加默認資源,因爲即使沒有默認資源,Android系統也會尋找分辨率最合適的圖片。也因此最好的效果就是在圖片的三個文件夾裏,都放置相應的資源。這也就解釋了我們創建SDK4版本的Android工程時drawable相關的資源文件如此個別,沒有默認目錄。


四、Android工程師如何發現最匹配的資源。

Android系統依據當前運行的環境選擇特定的資源。爲了顯示android是如何工作的,假設以下資源目錄分別存放着不用版本的圖片:

drawable/
drawable-en/
drawable-fr-rCA/
drawable-en-port/
drawable-en-notouch-12key/
drawable-port-ldpi/
drawable-port-notouch-12key/
而且假設具有如下環境:

場所 Locale = en-GB
屏幕方向 Screen orientation = port
屏幕分辨率 Screen pixel density = hdpi
觸摸屏模式 Touchscreen type = notouch
首選文本輸入方法 Primary text input method = 12key

最終Android系統選擇了drawable-en-port文件夾內的圖片。

選擇流程如下:

1、排除與當前環境衝突的資源

drawable/
drawable-en/
drawable-fr-rCA/
drawable-en-port/
drawable-en-notouch-12key/
drawable-port-ldpi/
drawable-port-notouch-12key/
例外:drawable類型的資源不會因爲衝突而被排除,詳見 Supporting MultipleScreens

2、根據表2,從上自下挑選出最高優先級的限制詞。

3、再看我們備選的資源目錄裏是否含有這個限制詞,如果含有進入第4步,如果沒有回到第2步,選擇下一個限制詞。

4、排除不含有我們挑選出的限定詞的資源目錄。

drawable/
drawable-en/
drawable-en-port/
drawable-en-notouch-12key/
drawable-port-ldpi/
drawable-port-notouch-12key/
例外:依舊是drawable,系統會挑選出最接近的屏幕密度的圖片,不管是否存在這個屏幕密度的限定詞。而且通常系統會選擇更大的圖片。

5、重複上述步驟,直到只剩下一個限定詞。

drawable-en/
drawable-en-port/
drawable-en-notouch-12key/

                                           

儘管這種工作模式可以響應所有資源的請求,但系統還是會考慮其他方面的影響。最優化的方案是一旦設備環境確定,就會永遠的排除一些衝突的資源目錄,即建立一個可用的資源目錄池。

當依據屏幕大小的限定詞時,如果沒有最合適的資源,系統會選擇偏小的資源,以避免選擇偏大的資源,而是程序崩潰。

注意:限定詞在表2的順序即限定詞優先級比資源目錄含有的限定詞的多少更加重要。
















發佈了61 篇原創文章 · 獲贊 3 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章