天天看點

android尋找最适合資源過程

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:

And assume the following is the device configuration:

Locale = <code>en-GB</code> 

Screen orientation = <code>port</code> 

Screen pixel density = <code>hdpi</code> 

Touchscreen type = <code>notouch</code> 

Primary text input method = <code>12key</code>

By comparing the device configuration to the available alternative resources, Android selects drawables from <code>drawable-en-port</code>.

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.

Eliminate resource files that contradict the device configuration.

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

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.

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:

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:

The remaining directory is <code>drawable-en-port</code>.

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 larger than 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 <code>xlarge</code> qualifier, but the device is a normal-size screen).

繼續閱讀