Supporting Multiple Screens

refs:

http://developer.android.com/guide/practices/screens_support.html


Android runs on a variety of devices that offer different screen sizes and densities. Forapplications, the Android system provides a consistent development environment across devices andhandles most of the work to adjust each application's user interface to the screen on which it isdisplayed. At the same time, the system provides APIs that allow you to control yourapplication's UI for specific screen sizes and densities, in order to optimize your UIdesign for different screen configurations. For example, you might want a UI for tabletsthat's different from the UI for handsets.

Although the system performs scaling and resizing to make your application work ondifferent screens, you should make the effort to optimize your application for different screensizes and densities. In doing so, you maximize the user experience for all devices and your usersbelieve that your application was actually designed for their devices—rather thansimply stretched to fit the screen on their devices.

By following the practices described in this document, you can create an application thatdisplays properly and provides an optimized user experience on all supported screen configurations,using a single .apk file.

Note: The information in this document assumes that yourapplication is designed for Android 1.6 (API Level 4) or higher. If your application supportsAndroid 1.5 or lower, please first read Strategies for Android 1.5.

Also, be aware that Android 3.2 has introduced new APIs that allow you to moreprecisely control the layout resources your application uses for different screen sizes. These newfeatures are especially important if you're developing an application that's optimized for tablets.For details, see the section about Declaring Tablet Layouts forAndroid 3.2.

Overview of Screens Support

This section provides an overview of Android's support for multiple screens, including: anintroduction to the terms and concepts used in this document and in the API, a summary of the screenconfigurations that the system supports, and an overview of the API and underlyingscreen-compatibility features.

Terms and concepts

Screen size
Actual physical size, measured as the screen's diagonal.

For simplicity, Android groups all actual screen sizes into four generalized sizes: small,normal, large, and extra-large.

Screen density
The quantity of pixels within a physical area of the screen; usually referred to as dpi (dotsper inch). For example, a "low" density screen has fewer pixels within a given physical area,compared to a "normal" or "high" density screen.

For simplicity, Android groups all actual screen densities into six generalized densities:low, medium, high, extra-high, extra-extra-high, and extra-extra-extra-high.

Orientation
The orientation of the screen from the user's point of view. This is either landscape orportrait, meaning that the screen's aspect ratio is either wide or tall, respectively. Be awarethat not only do different devices operate in different orientations by default, but theorientation can change at runtime when the user rotates the device.
Resolution
The total number of physical pixels on a screen. When adding support for multiple screens,applications do not work directly with resolution; applications should be concerned only with screensize and density, as specified by the generalized size and density groups.
Density-independent pixel (dp)
A virtual pixel unit that you should use when defining UI layout, to express layout dimensionsor position in a density-independent way.

The density-independent pixel is equivalent to one physical pixel on a 160 dpi screen, which isthe baseline density assumed by the system for a "medium" density screen. At runtime, the systemtransparently handles any scaling of the dp units, as necessary, based on the actual density of thescreen in use. The conversion of dp units to screen pixels is simple: px = dp * (dpi / 160) .For example, on a 240 dpi screen, 1 dp equals 1.5 physical pixels. You should always use dp unitswhen defining your application's UI, to ensure proper display of your UI on screens with differentdensities.

Range of screens supported

Starting with Android 1.6 (API Level 4), Android provides support for multiple screen sizes anddensities, reflecting the many different screen configurations that a device may have. You can usefeatures of the Android system to optimize your application's user interface for each screenconfiguration and ensure that your application not only renders properly, but provides the bestuser experience possible on each screen.

To simplify the way that you design your user interfaces for multiple screens, Android dividesthe range of actual screen sizes and densities into:

  • A set of four generalized sizes: small, normal,large,and xlarge

    Note: Beginning with Android 3.2 (API level 13), these size groupsare deprecated in favor of a new technique for managing screen sizes based on the available screenwidth. If you're developing for Android 3.2 and greater, see Declaring Tablet Layouts for Android 3.2 for moreinformation.

  • A set of six generalized densities:
    • ldpi (low) ~120dpi
    • mdpi (medium) ~160dpi
    • hdpi (high) ~240dpi
    • xhdpi (extra-high) ~320dpi
    • xxhdpi (extra-extra-high) ~480dpi
    • xxxhdpi (extra-extra-extra-high) ~640dpi

The generalized sizes and densities are arranged around abaseline configuration that is a normal size and mdpi (medium) density. Thisbaseline is based upon the screen configuration for the first Android-powered device, the T-MobileG1, which has an HVGA screen (until Android 1.6, this was the only screen configuration that Androidsupported).

Each generalized size and density spans a range of actual screen sizes and densities. For example,two devices that both report a screen size of normal might have actual screen sizes andaspect ratios that are slightly different when measured by hand. Similarly, two devices that reporta screen density of hdpi might have real pixel densities that are slightly different.Android makes these differences abstract to applications, so you can provide UI designed for thegeneralized sizes and densities and let the system handle any final adjustments as necessary. Figure1 illustrates how different sizes and densities are roughly categorized into the different sizeand density groups.

Figure 1.Illustration of how Android roughly maps actual sizes and densitiesto generalized sizes and densities (figures are not exact).

As you design your UI for different screen sizes, you'll discover that each design requires aminimum amount of space. So, each generalized screen size above has an associated minimumresolution that's defined by the system. These minimum sizes are in "dp" units—the same unitsyou should use when defining your layouts—which allows the system to avoid worrying aboutchanges in screen density.

  • xlarge screens are at least 960dp x 720dp
  • large screens are at least 640dp x 480dp
  • normal screens are at least 470dp x 320dp
  • small screens are at least 426dp x 320dp

Note: These minimum screen sizes were not as well defined prior toAndroid 3.0, so you may encounter some devices that are mis-classified between normal and large. These are also based on the physical resolution of the screen, so may vary across devices—forexample a 1024x720 tablet with a system bar actually has a bit less space available to theapplication due to it being used by the system bar.

To optimize your application's UI for the different screen sizes and densities, you can providealternativeresources for any of the generalized sizes and densities. Typically, you shouldprovide alternative layouts for some of the different screen sizes and alternative bitmap images fordifferent screen densities. At runtime, the system uses the appropriate resourcesfor your application, based on the generalized size or density of the current device screen.

You do not need to provide alternative resources for every combination of screen size anddensity. The system provides robust compatibility features that can handle most of the work ofrendering your application on any device screen, provided that you've implemented your UI usingtechniques that allow it to gracefully resize (as described in the Best Practices, below).

Note: The characteristics that define a device's generalized screensize and density are independent from each other. For example, a WVGA high-density screen isconsidered a normal size screen because its physical size is about the same as the T-Mobile G1(Android's first device and baseline screen configuration). On the other hand, a WVGA medium-densityscreen is considered a large size screen. Although it offers the same resolution (the same number ofpixels), the WVGA medium-density screen has a lower screen density, meaning that each pixel isphysically larger and, thus, the entire screen is larger than the baseline (normal size) screen.

Density independence

Your application achieves "density independence" when it preserves the physical size (fromthe user's point of view) of user interface elements when displayed on screens with differentdensities.

Maintaining density independence is important because, without it, a UI element (such as abutton) appears physically larger on a low-density screen and smaller on a high-density screen. Suchdensity-related size changes can cause problems in your application layout and usability. Figures 2and 3 show the difference between an application when it does not provide density independence andwhen it does, respectively.

Figure 2. Example application without support fordifferent densities, as shown on low, medium, and high-density screens.

Figure 3. Example application with good support fordifferent densities (it's density independent), as shown on low, medium, and highdensity screens.

The Android system helps your application achieve density independence in two ways:

  • The system scales dp units as appropriate for the current screen density
  • The system scales drawable resources to the appropriate size, based on the current screendensity, if necessary

In figure 2, the text view and bitmap drawable have dimensions specified in pixels (pxunits), so the views are physically larger on a low-density screen and smaller on a high-densityscreen. This is because although the actual screen sizes may be the same, the high-density screenhas more pixels per inch (the same amount of pixels fit in a smaller area). In figure 3, the layoutdimensions are specified in density-independent pixels (dp units). Because the baseline fordensity-independent pixels is a medium-density screen, the device with a medium-density screen looksthe same as it does in figure 2. For the low-density and high-density screens, however, the systemscales the density-independent pixel values down and up, respectively, to fit the screen asappropriate.

In most cases, you can ensure density independence in your application simply by specifying alllayout dimension values in density-independent pixels (dp units) or with "wrap_content", as appropriate. The system then scales bitmap drawables as appropriate in order todisplay at the appropriate size, based on the appropriate scaling factor for the current screen'sdensity.

However, bitmap scaling can result in blurry or pixelated bitmaps, which you might notice in theabove screenshots. To avoid these artifacts, you should provide alternative bitmap resources fordifferent densities. For example, you should provide higher-resolution bitmaps for high-densityscreens and the system will use those instead of resizing the bitmap designed for medium-densityscreens. The following section describes more about how to supply alternative resources fordifferent screen configurations.

How to Support Multiple Screens

The foundation of Android's support for multiple screens is its ability to manage the renderingof an application's layout and bitmap drawables in an appropriate way for the current screenconfiguration. The system handles most of the work to render your application properly on eachscreen configuration by scaling layouts to fit the screen size/density and scaling bitmap drawablesfor the screen density, as appropriate. To more gracefully handle different screen configurations,however, you should also:

  • Explicitly declare in the manifest which screen sizes your applicationsupports

    By declaring which screen sizes your application supports, you can ensure that onlydevices with the screens you support can download your application. Declaring support fordifferent screen sizes can also affect how the system draws your application on largerscreens—specifically, whether your application runs in screen compatibility mode.

    To declare the screen sizes your application supports, you should include the<supports-screens> element in your manifest file.

  • Provide different layouts for different screen sizes

    By default, Android resizes your application layout to fit the current device screen. In mostcases, this works fine. In other cases, your UI might not look as good and might need adjustmentsfor different screen sizes. For example, on a larger screen, you might want to adjust the positionand size of some elements to take advantage of the additional screen space, or on a smaller screen,you might need to adjust sizes so that everything can fit on the screen.

    The configuration qualifiers you can use to provide size-specific resources aresmall, normal, large, and xlarge. Forexample, layouts for an extra-large screen should go in layout-xlarge/.

    Beginning with Android 3.2 (API level 13), the above size groups are deprecated and youshould instead use the sw<N>dp configuration qualifier to define the smallestavailable width required by your layout resources. For example, if your multi-pane tablet layoutrequires at least 600dp of screen width, you should place it in layout-sw600dp/. Using thenew techniques for declaring layout resources is discussed further in the section about Declaring Tablet Layouts for Android 3.2.

  • Provide different bitmap drawables for different screen densities

    By default, Android scales your bitmap drawables (.png, .jpg, and .gif files) and Nine-Patch drawables (.9.png files) so that they render at the appropriatephysical size on each device. For example, if your application provides bitmap drawables only forthe baseline, medium screen density (mdpi), then the system scales them up when on a high-densityscreen, and scales them down when on a low-density screen. This scaling can cause artifacts in thebitmaps. To ensure your bitmaps look their best, you should include alternative versions atdifferent resolutions for different screen densities.

    The configuration qualifiers (described in detail below) that youcan use for density-specific resources are ldpi (low), mdpi (medium),hdpi (high), xhdpi extra-high), xxhdpi(extra-extra-high), and xxxhdpi (extra-extra-extra-high). For example, bitmapsfor high-density screens should go in drawable-hdpi/.

    Note: The mipmap-xxxhdpiqualifier is necessary only to provide a launcher icon that can appear larger than usual on anxxhdpi device. You do not need to provide xxxhdpi assets for all your app's images.

    Some devices scale-up the launcher icon by as much as 25%. For example, if your highestdensity launcher icon image is already extra-extra-high-density, the scaling process will make itappear less crisp. So you should provide a higher density launcher icon in themipmap-xxxhdpi directory, which the system uses instead of scaling up a smallerversion of the icon.

    See Provide anxxx-high-density launcher icon for more information. You should not use thexxxhdpi qualifier for UI elements other than the launcher icon.

Note: Place all your launcher icons in theres/mipmap-[density]/ folders, rather than the res/drawable-[density]/folders. The Android system retains the resources in these density-specific folders, such asmipmap-xxxhdpi, regardless of the screen resolution of the device where your app is installed. Thisbehavior allows launcher apps to pick the best resolution icon for your app to display on the homescreen. For more information about using the mipmap folders, seeManaging Projects Overview.

The size and density configuration qualifiers correspond to the generalized sizes and densitiesdescribed in Range of screens supported, above.

Note: If you're not familiar with configuration qualifiers and howthe system uses them to apply alternative resources, read ProvidingAlternative Resources for more information.

At runtime, the system ensures the best possible display on the current screen withthe following procedure for any given resource:

  1. The system uses the appropriate alternative resource

    Based on the size and density of the current screen, the system uses any size- anddensity-specific resource provided in your application. For example, if the device has ahigh-density screen and the application requests a drawable resource, the system looks for adrawable resource directory that best matches the device configuration. Depending on the otheralternative resources available, a resource directory with the hdpi qualifier (such asdrawable-hdpi/) might be the best match, so the system uses the drawable resource from thisdirectory.

  2. If no matching resource is available, the system uses the default resource and scales it upor down as needed to match the current screen size and density

    The "default" resources are those that are not tagged with a configuration qualifier. Forexample, the resources in drawable/ are the default drawable resources. The systemassumes that default resources are designed for the baseline screen size and density, which is anormal screen size and a medium-density. As such, the system scales default densityresources up for high-density screens and down for low-density screens, as appropriate.

    However, when the system is looking for a density-specific resource and does not find it inthe density-specific directory, it won't always use the default resources. The system mayinstead use one of the other density-specific resources in order to provide better resultswhen scaling. For example, when looking for a low-density resource and it is not available, thesystem prefers to scale-down the high-density version of the resource, because thesystem can easily scale a high-density resource down to low-density by a factor of 0.5, withfewer artifacts, compared to scaling a medium-density resource by a factor of 0.75.

For more information about how Android selects alternative resources by matching configurationqualifiers to the device configuration, readHow AndroidFinds the Best-matching Resource.

Using configuration qualifiers

Android supports several configuration qualifiers that allow you to control how the systemselects your alternative resources based on the characteristics of the current device screen. Aconfiguration qualifier is a string that you can append to a resource directory in your Androidproject and specifies the configuration for which the resources inside are designed.

To use a configuration qualifier:

  1. Create a new directory in your project's res/ directory and name it using theformat: <resources_name>-<qualifier>
    • <resources_name> is the standard resource name (such as drawable orlayout).
    • <qualifier> is a configuration qualifier from table 1, below, specifying thescreen configuration for which these resources are to be used (such as hdpi or xlarge).

    You can use more than one <qualifier> at a time—simply separate eachqualifier with a dash.

  2. Save the appropriate configuration-specific resources in this new directory. The resourcefiles must be named exactly the same as the default resource files.

For example, xlarge is a configuration qualifier for extra-large screens. When you appendthis string to a resource directory name (such as layout-xlarge), it indicates to thesystem that these resources are to be used on devices that have an extra-large screen.

Table 1. Configuration qualifiers that allow you toprovide special resources for different screen configurations.

Screen characteristicQualifierDescription
SizesmallResources for small size screens.
normalResources for normal size screens. (This is the baseline size.)
largeResources for large size screens.
xlargeResources for extra-large size screens.
DensityldpiResources for low-density (ldpi) screens (~120dpi).
mdpiResources for medium-density (mdpi) screens (~160dpi). (This is the baselinedensity.)
hdpiResources for high-density (hdpi) screens (~240dpi).
xhdpiResources for extra-high-density (xhdpi) screens (~320dpi).
xxhdpiResources for extra-extra-high-density (xxhdpi) screens (~480dpi).
xxxhdpiResources for extra-extra-extra-high-density (xxxhdpi) uses (~640dpi). Use this for the launcher icon only, see note above.
nodpiResources for all densities. These are density-independent resources. The system does notscale resources tagged with this qualifier, regardless of the current screen's density.
tvdpiResources for screens somewhere between mdpi and hdpi; approximately 213dpi. This is notconsidered a "primary" density group. It is mostly intended for televisions and most apps shouldn'tneed it—providing mdpi and hdpi resources is sufficient for most apps and the system willscale them as appropriate. If you find it necessary to provide tvdpi resources, you should size themat a factor of 1.33*mdpi. For example, a 100px x 100px image for mdpi screens should be 133px x133px for tvdpi.
OrientationlandResources for screens in the landscape orientation (wide aspect ratio).
portResources for screens in the portrait orientation (tall aspect ratio).
Aspect ratiolongResources for screens that have a significantly taller or wider aspect ratio (when in portraitor landscape orientation, respectively) than the baseline screen configuration.
notlongResources for use screens that have an aspect ratio that is similar to the baseline screenconfiguration.

Note: If you're developing your application for Android 3.2 andhigher, see the section about Declaring Tablet Layouts for Android 3.2 for information aboutnew configuration qualifiers that you should use when declaring layout resources for specificscreen sizes (instead of using the size qualifiers in table 1).

For more information about how these qualifiers roughly correspond to real screensizes and densities, see Range of Screens Supported, earlier in thisdocument.

For example, the following application resource directories provide different layout designsfor different screen sizes and different drawables. Use the mipmap/ folders forlauncher icons.

res/layout/my_layout.xml              // layout for normal screen size ("default")
res/layout-large/my_layout.xml        // layout for large screen size
res/layout-xlarge/my_layout.xml       // layout for extra-large screen size
res/layout-xlarge-land/my_layout.xml  // layout for extra-large in landscape orientation

res/drawable-mdpi/graphic.png         // bitmap for medium-density
res/drawable-hdpi/graphic.png         // bitmap for high-density
res/drawable-xhdpi/graphic.png        // bitmap for extra-high-density
res/drawable-xxhdpi/graphic.png       // bitmap for extra-extra-high-density

res/mipmap-mdpi/my_icon.png         // launcher icon for medium-density
res/mipmap-hdpi/my_icon.png         // launcher icon for high-density
res/mipmap-xhdpi/my_icon.png        // launcher icon for extra-high-density
res/mipmap-xxhdpi/my_icon.png       // launcher icon for extra-extra-high-density
res/mipmap-xxxhdpi/my_icon.png      // launcher icon for extra-extra-extra-high-density

For more information about how to use alternative resources and a complete list ofconfiguration qualifiers (not just for screen configurations), seeProviding Alternative Resources.

Be aware that, when the Android system picks which resources to use at runtime, it usescertain logic to determine the "best matching" resources. That is, the qualifiers you use don'thave to exactly match the current screen configuration in all cases in order for the system touse them. Specifically, when selecting resources based on the size qualifiers, the system willuse resources designed for a screen smaller than the current screen if there are no resourcesthat better match (for example, a large-size screen will use normal-size screen resources ifnecessary). 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 deviceconfiguration (for example, if all layout resources are tagged with the xlarge qualifier,but the device is a normal-size screen). For more information about how the system selectsresources, read How Android Finds theBest-matching Resource.

Tip: If you have some drawable resources that the systemshould never scale (perhaps because you perform some adjustments to the image yourself atruntime), you should place them in a directory with the nodpi configuration qualifier.Resources with this qualifier are considered density-agnostic and the system will not scalethem.

Designing alternative layouts and drawables

The types of alternative resources you should create depends on your application's needs.Usually, you should use the size and orientation qualifiers to provide alternative layout resourcesand use the density qualifiers to provide alternative bitmap drawable resources.

The following sections summarize how you might want to use the size and density qualifiers toprovide alternative layouts and drawables, respectively.

Alternative layouts

Generally, you'll know whether you need alternative layouts for different screen sizes onceyou test your application on different screen configurations. For example:

  • When testing on a small screen, you might discover that your layout doesn't quite fit on thescreen. For example, a row of buttons might not fit within the width of the screen on a small screendevice. In this case you should provide an alternative layout for small screens that adjusts thesize or position of the buttons.
  • When testing on an extra-large screen, you might realize that your layout doesn't makeefficient use of the big screen and is obviously stretched to fill it.In this case, you should provide an alternative layout for extra-large screens that provides aredesigned UI that is optimized for bigger screens such as tablets.

    Although your application should work fine without an alternative layout on big screens, it'squite important to users that your application looks as though it's designed specifically for theirdevices. If the UI is obviously stretched, users are more likely to be unsatisfied with theapplication experience.

  • And, when testing in the landscape orientation compared to the portrait orientation, youmight notice that UI elements placed at the bottom of the screen for the portrait orientationshould instead be on the right side of the screen in landscape orientation.

To summarize, you should be sure that your application layout:

  • Fits on small screens (so users can actually use your application)
  • Is optimized for bigger screens to take advantage of the additional screen space
  • Is optimized for both landscape and portrait orientations

If your UI uses bitmaps that need to fit the size of a view even after the system scalesthe layout (such as the background image for a button), you should use Nine-Patch bitmap files. ANine-Patch file is basically a PNG file in which you specify two-dimensional regions that arestretchable. When the system needs to scale the view in which the bitmap is used, the systemstretches the Nine-Patch bitmap, but stretches only the specified regions. As such, you don'tneed to provide different drawables for different screen sizes, because the Nine-Patch bitmap canadjust to any size. You should, however, provide alternate versions of your Nine-Patch files fordifferent screen densities.

Alternative drawables

Figure 4. Relative sizes for bitmap drawablesthat support each density.

Almost every application should have alternative drawable resources for different screendensities, because almost every application has a launcher icon and that icon should look good onall screen densities. Likewise, if you include other bitmap drawables in your application (suchas for menu icons or other graphics in your application), you should provide alternative versions oreach one, for different densities.

Note: You only need to provide density-specific drawables forbitmap files (.png, .jpg, or .gif) and Nine-Patch files (.9.png). If you use XML files to define shapes, colors, or other drawable resources, you shouldput one copy in the default drawable directory (drawable/).

To create alternative bitmap drawables for different densities, you should follow the3:4:6:8:12:16 scaling ratio between the six generalized densities. For example, if you havea bitmap drawable that's 48x48 pixels for medium-density screens, all the different sizes should be:

  • 36x36 (0.75x) for low-density
  • 48x48 (1.0x baseline) for medium-density
  • 72x72 (1.5x) for high-density
  • 96x96 (2.0x) for extra-high-density
  • 180x180 (3.0x) for extra-extra-high-density
  • 192x192 (4.0x) for extra-extra-extra-high-density (launcher icon only; see note above)

For more information about designing icons, see the Icon Design Guidelines,which includes size information for various bitmap drawables, such as launcher icons, menuicons, status bar icons, tab icons, and more.

Declaring Tablet Layouts for Android 3.2

For the first generation of tablets running Android 3.0, the proper way to declare tabletlayouts was to put them in a directory with the xlarge configuration qualifier (for example, res/layout-xlarge/). In order to accommodate other types of tablets and screensizes—in particular, 7" tablets—Android 3.2 introduces a new way to specify resourcesfor more discrete screen sizes. The new technique is based on the amount of space your layout needs(such as 600dp of width), rather than trying to make your layout fit the generalized size groups(such as large or xlarge).

The reason designing for 7" tablets is tricky when using the generalized size groups isthat a 7" tablet is technically in the same group as a 5" handset (the large group). Whilethese two devices are seemingly close to each other in size, the amount of space for anapplication's UI is significantly different, as is the style of user interaction. Thus, a 7" and 5"screen should not always use the same layout. To make it possible for you to provide differentlayouts for these two kinds of screens, Android now allows you to specify your layout resourcesbased on the width and/or height that's actually available for your application's layout, specifiedin dp units.

For example, after you've designed the layout you want to use for tablet-style devices, you mightdetermine that the layout stops working well when the screen is less than 600dp wide. This thresholdthus becomes the minimum size that you require for your tablet layout. Assuch, you can now specify that these layout resources should be used only when there is at least600dp of width available for your application's UI.

You should either pick a width and design to it as your minimum size, or test what is thesmallest width your layout supports once it's complete.

Note: Remember that all the figures used with these new size APIsare density-independent pixel (dp) values and your layout dimensions should also always be definedusing dp units, because what you care about is the amount of screen space available after the systemaccounts for screen density (as opposed to using raw pixel resolution). For more information aboutdensity-independent pixels, read Terms and concepts, earlier in thisdocument.

Using new size qualifiers

The different resource configurations that you can specify based on the space available for yourlayout are summarized in table 2. These new qualifiers offer you more control over the specificscreen sizes your application supports, compared to the traditional screen size groups (small,normal, large, and xlarge).

Note: The sizes that you specify using these qualifiers arenot the actual screen sizes. Rather, the sizes are for the width or height in dpunits that are available to your activity's window. The Android systemmight use some of the screen for system UI (such as the system bar at the bottom of the screen orthe status bar at the top), so some of the screen might not be available for your layout. Thus, thesizes you declare should be specifically about the sizes needed by your activity—the systemaccounts for any space used by system UI when declaring how much space it provides for your layout.Also beware that the Action Bar is considereda part of your application's window space, although your layout does not declare it, so it reducesthe space available for your layout and you must account for it in your design.

Table 2. New configuration qualifiers for screen size(introduced in Android 3.2).

Screen configurationQualifier valuesDescription
smallestWidthsw<N>dp

Examples:
sw600dp
sw720dp

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's 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 qualifier 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.

This is an alternative to the generalized screen size qualifiers (small, normal, large, xlarge)that allows you to define a discrete number for the effective size available for your UI.Using smallestWidth to determine the general screen size is useful because width isoften the driving factor in designing a layout. A UI will often scroll vertically, but have fairlyhard constraints on the minimum space it needs horizontally. The available width is also the keyfactor in determining whether to use a one-pane layout for handsets or multi-pane layout fortablets. Thus, you likely care most about what the smallest possible width will be on eachdevice.

Available screen widthw<N>dp

Examples:
w720dp
w1024dp

Specifies a minimum available width in dp units at which the resources should beused—defined by the <N> value. The system's corresponding value for thewidth changes when the screen's orientation switches between landscape and portrait toreflect the current actual width that's available for your UI.

This is often useful to determine whether to use a multi-pane layout, because even on atablet device, you often won't want the same multi-pane layout for portrait orientation as you dofor landscape. Thus, you can use this to specify the minimum width required for the layout, insteadof using both the screen size and orientation qualifiers together.

Available screen heighth<N>dp

Examples:
h720dp
h1024dp
etc.

Specifies a minimum screen height in dp units at which the resources should beused—defined by the <N> value. The system's corresponding value forthe height changes when the screen's orientation switches between landscape and portrait toreflect the current actual height that's available for your UI.

Using this to define theheight required by your layout is useful in the same way as w<N>dp is fordefining the required width, instead of using both the screen size and orientation qualifiers.However, most apps won't need this qualifier, considering that UIs often scroll vertically and arethus more flexible with how much height is available, whereas the width is more rigid.

While using these qualifiers might seem more complicated than using screen size groups, it shouldactually be simpler once you determine the requirements for your UI. When you design your UI,the main thing you probably care about is the actual size at which your application switches betweena handset-style UI and a tablet-style UI that uses multiple panes. The exact point of this switchwill depend on your particular design—maybe you need a 720dp width for your tablet layout,maybe 600dp is enough, or 480dp, or some number between these. Using these qualifiers in table 2,you are in control of the precise size at which your layout changes.

For more discussion about these size configuration qualifiers, see the Providing Resources document.

Configuration examples

To help you target some of your designs for different types of devices, here are somenumbers for typical screen widths:

  • 320dp: a typical phone screen (240x320 ldpi, 320x480 mdpi, 480x800 hdpi, etc).
  • 480dp: a tweener tablet like the Streak (480x800 mdpi).
  • 600dp: a 7” tablet (600x1024 mdpi).
  • 720dp: a 10” tablet (720x1280 mdpi, 800x1280 mdpi, etc).

Using the size qualifiers from table 2, your application can switch between your different layoutresources for handsets and tablets using any number you want for width and/or height. For example,if 600dp is the smallest available width supported by your tablet layout, you can provide these twosets of layouts:

res/layout/main_activity.xml           # For handsets
res/layout-sw600dp/main_activity.xml   # For tablets

In this case, the smallest width of the available screen space must be 600dp in order for thetablet layout to be applied.

For other cases in which you want to further customize your UI to differentiate between sizessuch as 7” and 10” tablets, you can define additional smallest width layouts:

res/layout/main_activity.xml           # For handsets (smaller than 600dp available width)
res/layout-sw600dp/main_activity.xml   # For 7” tablets (600dp wide and bigger)
res/layout-sw720dp/main_activity.xml   # For 10” tablets (720dp wide and bigger)

Notice that the previous two sets of example resources use the "smallest width" qualifier, sw<N>dp, which specifies the smallest of the screen's two sides, regardless of thedevice's current orientation. Thus, using sw<N>dp is a simple way to specify theoverall screen size available for your layout by ignoring the screen's orientation.

However, in some cases, what might beimportant for your layout is exactly how much width or height is currently available. Forexample, if you have a two-pane layout with two fragments side by side, you might want to use itwhenever the screen provides at least 600dp of width, whether the device is in landscape orportrait orientation. In this case, your resources might look like this:

res/layout/main_activity.xml         # For handsets (smaller than 600dp available width)
res/layout-w600dp/main_activity.xml  # Multi-pane (any screen with 600dp available width or more)

Notice that the second set is using the "available width" qualifier, w<N>dp. Thisway, one device may actually use both layouts, depending on the orientation of the screen (ifthe available width is at least 600dp in one orientation and less than 600dp in the otherorientation).

If the available height is a concern for you, then you can do the same using the h<N>dp qualifier. Or, even combine the w<N>dp and h<N>dpqualifiers if you need to be really specific.

Declaring screen size support

Once you've implemented your layouts for different screen sizes, it's equally important that youdeclare in your manifest file which screens your application supports.

Along with the new configuration qualifiers for screen size, Android 3.2 introduces newattributes for the <supports-screens>manifest element:

android:requiresSmallestWidthDp
Specifies the minimum smallestWidth required. The smallestWidth is the shortest dimension ofthe screen space (in dp units) that must be available to your application UI—that is,the shortest of the available screen's two dimensions. So, in order for a device to be consideredcompatible with your application, the device's smallestWidth must be equal to or greater than thisvalue. (Usually, the value you supply for this is the "smallest width" that your layout supports,regardless of the screen's current orientation.)

For example, if your application is only for tablet-style devices with a 600dpsmallest available width:

<manifest ... >
    <supports-screens android:requiresSmallestWidthDp="600" />
    ...
</manifest>

However, if your application supports all screen sizes supported by Android (as small as426dp x 320dp), then you don't need to declare this attribute, because the smallest width yourapplication requires is the smallest possible on any device.

Caution: The Android system does not pay attention to thisattribute, so it does not affect how your application behaves at runtime. Instead, it is usedto enable filtering for your application on services such as Google Play. However,Google Play currently does not support this attribute for filtering (on Android3.2), so you should continue using the other size attributes if your application does not supportsmall screens.

android:compatibleWidthLimitDp
This attribute allows you to enable screen compatibility mode as auser-optional feature by specifying the maximum "smallest width" that your applicationsupports. If the smallest side of a device's available screen is greater than your value here,users can still install your application, but are offered to run it in screen compatibility mode. Bydefault, screen compatibility mode is disabled and your layout is resized to fit the screen asusual, but a button is available in the system bar that allows users to toggle screen compatibilitymode on and off.

Note: If your application's layout properly resizes for largescreens, you do not need to use this attribute. We recommend that you avoid using thisattribute and instead ensure your layout resizes for larger screens by following therecommendations in this document.

android:largestWidthLimitDp
This attribute allows you to force-enable screen compatibility mode by specifyingthe maximum "smallest width" that your application supports. If the smallestside of a device's available screen is greater than your value here, the application runs in screencompatibility mode with no way for the user to disable it.

Note: If your application's layout properly resizes for largescreens, you do not need to use this attribute. We recommend that you avoid using thisattribute and instead ensure your layout resizes for larger screens by following therecommendations in this document.

Caution: When developing for Android 3.2 and higher, youshould not use the older screen size attributes in combination with the attributeslisted above. Using both the new attributes and the older size attributes might causeunexpected behavior.

For more information about each of these attributes, follow the respective links above.

Best Practices

The objective of supporting multiple screens is to create an application that can functionproperly and look good on any of the generalized screen configurations supported by Android. Theprevious sections of this document provide information about how Android adapts yourapplication to screen configurations and how you can customize the look of your application ondifferent screen configurations. This section provides some additional tips and an overview oftechniques that help ensure that your application scales properly for different screenconfigurations.

Here is a quick checklist about how you can ensure that your application displays properlyon different screens:

  1. Use wrap_content, fill_parent, or dp units when specifyingdimensions in an XML layout file
  2. Do not use hard coded pixel values in your application code
  3. Do not use AbsoluteLayout (it's deprecated)
  4. Supply alternative bitmap drawables for different screen densities

The following sections provide more details.

1. Use wrap_content, fill_parent, or the dp unit for layout dimensions

When defining the android:layout_width and android:layout_height forviews in an XML layout file, using "wrap_content","fill_parent" or dp units guarantees that the view isgiven an appropriate size on the current device screen.

For instance, a view with a layout_width="100dp" measures 100 pixels wide onmedium-density screen and the system scales it up to 150 pixels wide on high-density screen, sothat the view occupies approximately the same physical space on the screen.

Similarly, you should prefer the sp (scale-independent pixel) to define textsizes. The sp scale factor depends on a user setting and the system scales thesize the same as it does for dp.

2. Do not use hard-coded pixel values in your application code

For performance reasons and to keep the code simpler, the Android system uses pixels as thestandard unit for expressing dimension or coordinate values. That means that the dimensions of aview are always expressed in the code using pixels, but always based on the current screen density.For instance, if myView.getWidth() returns 10, the view is 10 pixels wide on thecurrent screen, but on a device with a higher density screen, the value returned might be 15. If youuse pixel values in your application code to work with bitmaps that are not pre-scaled for thecurrent screen density, you might need to scale the pixel values that you use in your code to matchthe un-scaled bitmap source.

If your application manipulates bitmaps or deals with pixel values at runtime, see the sectionbelow about Additional Density Considerations.

3. Do not use AbsoluteLayout

Unlike the other layouts widgets, AbsoluteLayout enforcesthe use of fixed positions to lay out its child views, which can easily lead to user interfaces thatdo not work well on different displays. Because of this, AbsoluteLayout wasdeprecated in Android 1.5 (API Level 3).

You should instead use RelativeLayout, which uses relative positioningto lay out its child views. For instance, you can specify that a button widget should appear "tothe right of" a text widget.

4. Use size and density-specific resources

Although the system scales your layout and drawable resources based on the current screenconfiguration, you may want to make adjustments to the UI on different screen sizes and providebitmap drawables that are optimized for different densities. This essentially reiterates theinformation from earlier in this document.

If you need to control exactly how your application will look on variousscreen configurations, adjust your layouts and bitmap drawables in configuration-specificresource directories. For example, consider an icon that you want to display onmedium and high-density screens. Simply create your icon at two different sizes(for instance 100x100 for medium-density and 150x150 for high-density) and putthe two variations in the appropriate directories, using the properqualifiers:

res/drawable-mdpi/icon.png   //for medium-density screens
res/drawable-hdpi/icon.png   //for high-density screens

Note: If a density qualifier is not defined in a directory name,the system assumes that the resources in that directory are designed for the baseline mediumdensity and will scale for other densities as appropriate.

For more information about valid configuration qualifiers, see Usingconfiguration qualifiers, earlier in this document.

Additional Density Considerations

This section describes more about how Android performs scaling for bitmap drawables on differentscreen densities and how you can further control how bitmaps are drawn on different densities. Theinformation in this section shouldn't be important to most applications, unless you have encounteredproblems in your application when running on different screen densities or your applicationmanipulates graphics.

To better understand how you can support multiple densities when manipulating graphics atruntime, you should understand that the system helps ensure the proper scale for bitmaps in thefollowing ways:

  1. Pre-scaling of resources (such as bitmap drawables)

    Based on the density of the current screen, the system uses any size- or density-specificresources from your application and displays them without scaling. If resources are not available inthe correct density, the system loads the default resources and scales them up or down as needed tomatch the current screen's density. The system assumes that default resources (those from adirectory without configuration qualifiers) are designed for the baseline screen density (mdpi),unless they are loaded from a density-specific resource directory. Pre-scaling is, thus, what thesystem does when resizing a bitmap to the appropriate size for the current screendensity.

    If you request the dimensions of a pre-scaled resource, the system returns valuesrepresenting the dimensions after scaling. For example, a bitmap designed at 50x50 pixelsfor an mdpi screen is scaled to 75x75 pixels on an hdpi screen (if there is no alternative resourcefor hdpi) and the system reports the size as such.

    There are some situations in which you might not want Android to pre-scalea resource. The easiest way to avoid pre-scaling is to put the resource in a resource directorywith the nodpi configuration qualifier. For example:

    res/drawable-nodpi/icon.png

    When the system uses the icon.png bitmap from this folder, it does not scale itbased on the current device density.

  2. Auto-scaling of pixel dimensions and coordinates

    An application can disable pre-scaling by setting android:anyDensity to "false" in the manifest or programmatically for a Bitmap by setting inScaled to"false". In this case, the system auto-scales any absolute pixel coordinates and pixeldimension values at draw time. It does this to ensure that pixel-defined screen elements are stilldisplayed at approximately the same physical size as they would be at the baseline screen density(mdpi). The system handles this scaling transparently to the application and reports the scaledpixel dimensions to the application, rather than physical pixel dimensions.

    For instance, suppose a device has a WVGA high-density screen, which is 480x800 and about thesame size as a traditional HVGA screen, but it's running an application that has disabledpre-scaling. In this case, the system will "lie" to the application when it queries for screendimensions, and report 320x533 (the approximate mdpi translation for the screen density). Then, whenthe application does drawing operations, such as invalidating the rectangle from (10,10) to (100,100), the system transforms the coordinates by scaling them the appropriate amount, and actuallyinvalidate the region (15,15) to (150, 150). This discrepancy may cause unexpected behavior ifyour application directly manipulates the scaled bitmap, but this is considered a reasonabletrade-off to keep the performance of applications as good as possible. If you encounter thissituation, read the following section about Converting dp units to pixelunits.

    Usually, you should not disable pre-scaling. The best way to support multiplescreens is to follow the basic techniques described above in How to SupportMultiple Screens.

If your application manipulates bitmaps or directly interacts with pixels on the screen in someother way, you might need to take additional steps to support different screen densities. Forexample, if you respond to touch gestures by counting the number of pixels that a fingercrosses, you need to use the appropriate density-independent pixel values, instead of actualpixels.

Scaling Bitmap objects created at runtime

Figure 5. Comparison of pre-scaled and auto-scaledbitmaps.

If your application creates an in-memory bitmap (a Bitmap object), thesystem assumes that the bitmap is designed for the baseline medium-density screen, by default, andauto-scales the bitmap at draw time. The system applies "auto-scaling" to a Bitmap when the bitmap has unspecified density properties. If you don't properlyaccount for the current device's screen density and specify the bitmap's density properties, theauto-scaling can result in scaling artifacts the same as when you don't provide alternativeresources.

To control whether a Bitmap created at runtime is scaled or not, you canspecify the density of the bitmap with setDensity(),passing a density constant from DisplayMetrics, such as DENSITY_HIGH or DENSITY_LOW.

If you're creating a Bitmap using BitmapFactory, such as from a file or a stream, you can use BitmapFactory.Options to define properties of the bitmap asit already exists, which determine if or how the system will scale it. For example, you can use theinDensity field to define the density for which thebitmap is designed and the inScaled field to specify whether the bitmap should scale tomatch the current device's screen density.

If you set the inScaled field to false, then you disable anypre-scaling that the system may apply to the bitmap and the system will then auto-scale it at drawtime. Using auto-scaling instead of pre-scaling can be more CPU expensive, but usesless memory.

Figure 5 demonstrates the results of the pre-scale and auto-scale mechanisms when loading low(120), medium (160) and high (240) density bitmaps on a high-density screen. The differences aresubtle, because all of the bitmaps are being scaled to match the current screen density, however thescaled bitmaps have slightly different appearances depending on whether they are pre-scaled orauto-scaled at draw time.

Note: In Android 3.0 and above, there should be no perceivabledifference between pre-scaled and auto-scaled bitmaps, due to improvements in the graphicsframework.

Converting dp units to pixel units

In some cases, you will need to express dimensions in dp and then convert them topixels. Imagine an application in which a scroll or fling gesture is recognized after the user'sfinger has moved by at least 16 pixels. On a baseline screen, a user's must move by 16 pixels/ 160 dpi, which equals 1/10th of an inch (or 2.5 mm) before the gesture is recognized. On a devicewith a high-density display (240dpi), the user's must move by 16 pixels / 240 dpi, whichequals 1/15th of an inch (or 1.7 mm). The distance is much shorter and the application thus appearsmore sensitive to the user.

To fix this issue, the gesture threshold must be expressed in code in dp and thenconverted to actual pixels. For example:

// The gesture threshold expressed in dp
private static final float GESTURE_THRESHOLD_DP = 16.0f;

// Get the screen's density scale
final float scale = getResources().getDisplayMetrics().density;
// Convert the dps to pixels, based on density scale
mGestureThreshold = (int) (GESTURE_THRESHOLD_DP * scale + 0.5f);

// Use mGestureThreshold as a distance in pixels...

The DisplayMetrics.density field specifies the scalefactor you must use to convert dp units to pixels, according to the current screen density.On a medium-density screen, DisplayMetrics.densityequals 1.0; on a high-density screen it equals 1.5; on an extra-high-density screen, it equals 2.0;and on a low-density screen, it equals 0.75. This figure is the factor by which you should multiplythe dp units on order to get the actual pixel count for the current screen. (Then add 0.5f to round the figure up to the nearest whole number, when converting to an integer.) For moreinformation, refer to the DisplayMetrics class.

However, instead of defining an arbitrary threshold for this kind of event, you shoulduse pre-scaled configuration values that are available from ViewConfiguration.

Using pre-scaled configuration values

You can use the ViewConfiguration class to access common distances,speeds, and times used by the Android system. For instance, thedistance in pixels used by the framework as the scroll threshold can be obtained with getScaledTouchSlop():

private static final int GESTURE_THRESHOLD_DP = ViewConfiguration.get(myContext).getScaledTouchSlop();

Methods in ViewConfiguration starting with the getScaled prefixare guaranteed to return a value in pixels that will display properly regardless of the currentscreen density.

How to Test Your Application on Multiple Screens

Figure 6. A set of AVDs for testing screens support.

Before publishing your application, you should thoroughly test it in all of the supported screensizes and densities. The Android SDK includes emulator skins you can use, whichreplicate the sizes and densities of common screen configurations on which your application islikely to run. You can also modify the default size, density, and resolution of the emulator skinsto replicate the characteristics of any specific screen. Using the emulator skins and additionalcustom configurations allows you to test any possible screen configuration, so you don'thave to buy various devices just to test your application's screen support.

To set up an environment for testing your application's screen support, you should create aseries of AVDs (Android Virtual Devices), using emulator skins and screen configurations thatemulate the screen sizes and densities you want your application to support. To do so, you can usethe AVD Manager to create the AVDs and launch them with a graphical interface.

To launch the Android SDK Manager, execute the SDK Manager.exe from your Android SDK directory (on Windows only) or execute android fromthe <sdk>/tools/ directory (on all platforms). Figure 6 shows the AVDManager with a selection of AVDs, for testing various screen configurations.

Table 3 shows the various emulator skins that are available in the Android SDK, which you can useto emulate some of the most common screen configurations.

For more information about creating and using AVDs to test your application, see Managing AVDs with AVDManager.

Table 3. Various screenconfigurations available from emulator skins in the Android SDK (indicated in bold) and otherrepresentative resolutions.

  Low density (120), ldpi Medium density (160), mdpi High density (240), hdpi Extra-high-density (320), xhdpi
Small screenQVGA (240x320) 480x640 
Normal screenWQVGA400 (240x400)
WQVGA432 (240x432)
HVGA (320x480)WVGA800 (480x800)
WVGA854 (480x854)

600x1024
640x960
Large screenWVGA800** (480x800)
WVGA854** (480x854)
WVGA800* (480x800)
WVGA854* (480x854)

600x1024
  
Extra-Large screen1024x600WXGA (1280x800)
1024x768
1280x768
1536x1152
1920x1152
1920x1200
2048x1536
2560x1536
2560x1600
* To emulate this configuration, specify acustom density of 160 when creating an AVD that uses a WVGA800 or WVGA854 skin.
** To emulate this configuration, specify a custom density of 120 when creating an AVD thatuses a WVGA800 or WVGA854 skin.
† This skin is available with the Android 3.0 platform

To see the relative numbers of active devices that support any given screen configuration, seethe Screen Sizes and Densitiesdashboard.

Figure 7. Size and density options you can set, when starting an AVD from the AVDManager.

We also recommend that you test your application in an emulator that is setup to run at a physical size that closely matches an actual device. This makesit a lot easier to compare the results at various sizes and densities. Todo so you need to know the approximate density, in dpi, of your computermonitor (for instance, a 30" Dell monitor has a density of about 96 dpi). When you launch an AVDfrom the AVD Manager, you can specify the screen size for the emulator and yourmonitor dpi in the Launch Options, as shown in figure 7.

If you would like to test your application on a screen that uses a resolutionor density not supported by the built-in skins, you can create an AVD that uses a custom resolutionor density. When creating the AVD from the AVD Manager, specify the Resolution,instead of selecting a Built-in Skin.

If you are launching your AVD from the command line, you can specify the scale forthe emulator with the -scale option. For example:

emulator -avd <avd_name> -scale 96dpi

To refine the size of the emulator, you can instead pass the -scale option a numberbetween 0.1 and 3 that represents the desired scaling factor.

For more information about creating AVDs from the command line, see Managing AVDs from theCommand Line.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值