码迷,mamicode.com
首页 > 移动开发 > 详细

Android 适配不同分辨率屏幕

时间:2016-04-29 15:49:49      阅读:1868      评论:0      收藏:0      [点我收藏+]

标签:

为了查看方便,特意贴一段 Google API 文档:http://developer.Android.com/intl/zh-cn/guide/practices/screens_support.html

文章末尾会附上该篇文档。


近期做些关于手机适配的工作。

下面来总结一下,希望可以对大家有帮助,本人能力有限,如果有解释失误的地方,请务必帮忙指出,谢谢。


首先引入几个概念。


PPI : Pixels Per Inch的缩写简称,表示的是每英寸显示屏所拥有的像素(pixel)数目。

DPI : Dots Per Inch , 最初用于衡量打印物上每英寸的点数密度,就是说你的打印机可以在一英寸内打多少个点。

DPI用来表示输出设备的输出精度,如打印机,显示器

DPI表示的是 像点/英寸(每英寸长度上有多少个打印点或像点)

PPI用来表示输入设备的输入精度,如扫描仪,数码相机

PPI表示的是 像素/英寸(每英寸长度上有多少个像素)


显然,在谈到Android设备屏幕时,用DPI 比较合适,官方文档中也是用DPI来说明的。当然,如果有人说成PPI,也并不妨碍理解,只是这种说法不太准确。

关于如何计算DPI ,下面我们拿三星S3为例。

根据三星官网给的 信息:

The S III‘s HD Super AMOLED display measures 4.8 inches (120 mm) on the diagonal. With a 720×1280-pixel (720p) resolution, its pixel per inch (PPI, a measure of pixel density) is a relatively high 306。

我们可知:分辨率为 720x1280(高宽比为16:9) , 4.8英寸 , 306dpi。

那么,这个dpi是如何计算出来的呢?

技术分享

由于对角线长为4.8英寸,我们要计算对角线上一共有多少像素点。

勾股定理可知:斜对角线的像素点 =   技术分享


进而求每英寸的像素点个数,即 技术分享(在Android中,大家把PPI 和 DPI 看成一个东西即可)

这么计算后可知,三星S3的DPI = 306. 即,该手机每英寸有306个像素点。


下面再介绍Android中非常重要的几个概念。

dp (或 dip) , Density-Independent Pixels. 按照字面意思:密度无关的像素点。

那么,何为Density?

先了解一下屏幕的级别:

屏幕级别

屏幕密度DPI

密度比值

像素量/英寸

通常的分辨率

ldpi

120

0.75

120

 240x400

mdpi

160

1

160

320x480

hdpi

240

1.5

240

480x800

xhdpi

320

2

320


xxhdpi

480

3

480


在这里,Android将mdpi 下 px:dp = 1:1换算。将其设置为baseline后,它的density为1.其他手机的density就能轻易算出来。

(可能有人会问为何dp是这么定义的?因为,Android历史第一部手机:T-mobile G1 就是这种分辨率)

技术分享(出自HTC,2010年停产,里程碑产品)

如果不是以上给出的这些通常的分辨率,那么我们如何确定它的DPI呢?

比如手机基伍A800 ,5.0英寸 , 分辨率为540x960 , 根据公式计算得出 DPI = 220,

那么,就近原则,它的屏幕密度被认为是240dpi , density = 1.5 , 找的相关资源图片在 drawable/hdpi 文件夹下。

如果想利用sw<N>dp来进行进一步的适配。那么,sw<N>dp 中的N如何计算?

Step1:
可以通过adb命令来快速获取手机的屏幕参数:
adb shell dumpsys window displays
(this command can get all display information, include resolution and dpi.)
通过该命令,我们可以取得手机的dpi(dot per inch),以及分辨率等。

Step2:
dp和px的换算公式: dp = (px * 160)/ dpi


注:这里的dpi是归化后的dpi,并非是真实的dpi。基伍A800的真实dpi为220dpi,归化后的dpi只有这几种:

  • 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

Android会取就近的dpi值,220离240最近,所以基伍A800的机器dpi为240.

拿A800 为例,屏幕分辨率为 960*540 ,dpi 为 240。
因为我们要计算sw<N>dp的N ,sw(smallest-width),即最小可用宽度。
所以该N的计算的公式: dp = (540*160)/ 240 = 360.
如果为480*800 、 480*854   dp = 480*160 / 240 = 320.
所以,A800在适配的时候,找到的dimen.xml是Res/values-sw360dp/dimen.xml

补充说明:
Android在适配的时候会找小于等于N的资源。
比如A800,其smallestWidth的N=360.如果你不是将资源放在Res/values-sw360dp/dimen.xml中,
而是放在Res/values-sw340dp/dimen.xml中。也不影响它正确适配。只是不够精确罢了。

如果某款手机的smallestWidth的N=300 ,都适配不到的情况下,Android将默认去res/values/dimen.xml中寻找。
为了防止crush,请在默认的dimen.xml中也配置上相应参数。

2015-06-25 再次补充:

在机型适配的时候,还会碰到更加棘手的问题。
比如:
三星S2的分辨率:480*800
小黄蜂hyf9300的分辨率:480*854
此时,小黄蜂的分辨率在竖直方向的高度比S2多了54像素点高度,而上述的sw<N>dp仅仅是针对smallestWidth的情况。
两款手机的sw均为320dp,不能很好的区分两款手机。此时该如何做呢?

谷歌在3.2以后推荐使用以下这几种方法来进行适配:

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

技术分享

技术分享
其中,h<N>dp是在该情况下可以用到的。但是,该处的N和sw<N>dp中的N有区别。
根据英文描述我们可以知道,此处的N和手机的orientation有关。
横竖屏切换时,N也随着变动,并且N值是指的是UI可用高度。这个地方的可用高度不包含systemUI占用的高度,诸如状态栏等。
也就是说,当你计算出竖直方向的高度后,还要减去系统UI所占用的高度(包括状态栏和titlebar等)。
除非你的应用已经设定orientation是固定的,这样你才可以放心地使用该方法来处理机型适配问题。

了解了上面的知识后,我们开始为下面3款机型适配。(下面所说的h<N>dp都是android:screenOrientation="portrait"的情况下

机型

分辨率

全屏高度h<N>dp

三星S2

480*800

N = 800*160/240 = 533.33dp

小黄蜂

480*854

N = 854*160/240 = 569.33dp

A800

540*960

N = 800*160/240 = 640dp

由于我们团队开发的应用只有状态栏是属于systemUI,所以该N还得减去状态栏的高度为25dp。

机型

分辨率

可用高度h<N>dp

三星S2

480*800

N = 533.33 - 25 = 508.33dp

小黄蜂

480*854

N = 569.33 - 25 = 544.33dp

A800

540*960

N = 640 - 25 = 615 dp

该h<N>dp的适配逻辑和sw<N>dp一样。

比如小黄蜂手机打开的应用检测出其可用高度为544.33dp,

先查找对应的文件夹即:values-h544.33dp/dimen.xml,如果没有找到,那么向下匹配。

实在找不到,最后才去values/dimen.xml中默认匹配。

所以,最后在保证可以查找到并且允许状态栏等高度小幅度变化的情况下,我们在代码中设定其高度为:

机型

分辨率

h<N>dp

对应的适配文件

三星S2

480*800

N = 500dp

values-h500dp/dimen.xml

小黄蜂

480*854

N = 540dp

values-h540dp/dimen.xml

A800

540*960

N = 610dp

values-h610dp/dimen.xml

当然,最后还是别忘了在values/dimen.xml文件中加入默认的配置,以防在找不到的情况下发生crush。


Android runs on a variety of devices that offer different screen sizes and densities. For applications, the Android system provides a consistent development environment across devices and handles most of the work to adjust each application‘s user interface to the screen on which it is displayed. At the same time, the system provides APIs that allow you to control your application‘s UI for specific screen sizes and densities, in order to optimize your UI design for different screen configurations. For example, you might want a UI for tablets that‘s different from the UI for handsets.

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

By following the practices described in this document, you can create an application that displays 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 your application is designed for Android 1.6 (API Level 4) or higher. If your application supports Android 1.5 or lower, please first readStrategies for Android 1.5

Also, be aware that Android 3.2 has introduced new APIs that allow you to more precisely control the layout resources your application uses for different screen sizes. These new features are especially important if you‘re developing an application that‘s optimized for tablets. For details, see the section aboutDeclaring Tablet Layouts for Android 3.2.

Overview of Screens Support

This section provides an overview of Android‘s support for multiple screens, including: an introduction to the terms and concepts used in this document and in the API, a summary of the screen configurations that the system supports, and an overview of the API and underlying screen-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 (dots per 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 or portrait, meaning that the screen‘s aspect ratio is either wide or tall, respectively. Be aware that not only do different devices operate in different orientations by default, but the orientation 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 screen size 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 dimensions or position in a density-independent way.

The density-independent pixel is equivalent to one physical pixel on a 160 dpi screen, which is the baseline density assumed by the system for a "medium" density screen. At runtime, the system transparently handles any scaling of the dp units, as necessary, based on the actual density of the screen 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 units when defining your application‘s UI, to ensure proper display of your UI on screens with different densities.

Range of screens supported

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

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

  • A set of four generalized sizessmallnormallarge, and xlarge

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

  • 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 a baseline configuration that is a normal size and mdpi(medium) density. This baseline is based upon the screen configuration for the first Android-powered device, the T-Mobile G1, which has an HVGA screen (until Android 1.6, this was the only screen configuration that Android supported).

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 and aspect ratios that are slightly different when measured by hand. Similarly, two devices that report a 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 the generalized sizes and densities and let the system handle any final adjustments as necessary. Figure 1 illustrates how different sizes and densities are roughly categorized into the different size and density groups.

技术分享

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

As you design your UI for different screen sizes, you‘ll discover that each design requires a minimum amount of space. So, each generalized screen size above has an associated minimum resolution that‘s defined by the system. These minimum sizes are in "dp" units—the same units you should use when defining your layouts—which allows the system to avoid worrying about changes 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 to Android 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—for example a 1024x720 tablet with a system bar actually has a bit less space available to the application due to it being used by the system bar.

To optimize your application‘s UI for the different screen sizes and densities, you can provide alternative resources for any of the generalized sizes and densities. Typically, you should provide alternative layouts for some of the different screen sizes and alternative bitmap images for different screen densities. At runtime, the system uses the appropriate resources for 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 and density. The system provides robust compatibility features that can handle most of the work of rendering your application on any device screen, provided that you‘ve implemented your UI using techniques that allow it to gracefully resize (as described in the Best Practices, below).

Note: The characteristics that define a device‘s generalized screen size and density are independent from each other. For example, a WVGA high-density screen is considered 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-density screen is considered a large size screen. Although it offers the same resolution (the same number of pixels), the WVGA medium-density screen has a lower screen density, meaning that each pixel is physically 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 (from the user‘s point of view) of user interface elements when displayed on screens with different densities.

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

技术分享

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

技术分享

Figure 3. Example application with good support for different densities (it‘s density independent), as shown on low, medium, and high density 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 screen density, if necessary

In figure 2, the text view and bitmap drawable have dimensions specified in pixels (px units), so the views are physically larger on a low-density screen and smaller on a high-density screen. This is because although the actual screen sizes may be the same, the high-density screen has more pixels per inch (the same amount of pixels fit in a smaller area). In figure 3, the layout dimensions are specified in density-independent pixels (dpunits). Because the baseline for density-independent pixels is a medium-density screen, the device with a medium-density screen looks the same as it does in figure 2. For the low-density and high-density screens, however, the system scales the density-independent pixel values down and up, respectively, to fit the screen as appropriate.

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

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

How to Support Multiple Screens

The foundation of Android‘s support for multiple screens is its ability to manage the rendering of an application‘s layout and bitmap drawables in an appropriate way for the current screen configuration. The system handles most of the work to render your application properly on each screen configuration by scaling layouts to fit the screen size/density and scaling bitmap drawables for 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 application supports

    By declaring which screen sizes your application supports, you can ensure that only devices with the screens you support can download your application. Declaring support for different screen sizes can also affect how the system draws your application on larger screens—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 most cases, this works fine. In other cases, your UI might not look as good and might need adjustments for different screen sizes. For example, on a larger screen, you might want to adjust the position and 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 are smallnormallarge, and xlarge. For example, 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 you should instead use the sw<N>dp configuration qualifier to define the smallest available width required by your layout resources. For example, if your multi-pane tablet layout requires at least 600dp of screen width, you should place it inlayout-sw600dp/. Using the new 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 appropriate physical size on each device. For example, if your application provides bitmap drawables only for the baseline, medium screen density (mdpi), then the system scales them up when on a high-density screen, and scales them down when on a low-density screen. This scaling can cause artifacts in the bitmaps. To ensure your bitmaps look their best, you should include alternative versions at different resolutions for different screen densities.

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

    Note: The mipmap-xxxhdpi qualifier is necessary only to provide a launcher icon that can appear larger than usual on an xxhdpi 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 highest density launcher icon image is already extra-extra-high-density, the scaling process will make it appear less crisp. So you should provide a higher density launcher icon in the mipmap-xxxhdpi directory, which the system uses instead of scaling up a smaller version of the icon.

    See Provide an xxx-high-density launcher icon for more information. You should not use the xxxhdpiqualifier for UI elements other than the launcher icon.

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

The size and density configuration qualifiers correspond to the generalized sizes and densities described inRange of screens supported, above.

Note: If you‘re not familiar with configuration qualifiers and how the system uses them to apply alternative resources, read Providing Alternative Resources for more information.

At runtime, the system ensures the best possible display on the current screen with the 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- and density-specific resource provided in your application. For example, if the device has a high-density screen and the application requests a drawable resource, the system looks for a drawable resource directory that best matches the device configuration. Depending on the other alternative resources available, a resource directory with the hdpi qualifier (such as drawable-hdpi/) might be the best match, so the system uses the drawable resource from this directory.

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

    The "default" resources are those that are not tagged with a configuration qualifier. For example, the resources in drawable/ are the default drawable resources. The system assumes that default resources are designed for the baseline screen size and density, which is a normal screen size and a medium-density. As such, the system scales default density resources 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 in the density-specific directory, it won‘t always use the default resources. The system may instead use one of the other density-specific resources in order to provide better results when scaling. For example, when looking for a low-density resource and it is not available, the system prefers to scale-down the high-density version of the resource, because the system can easily scale a high-density resource down to low-density by a factor of 0.5, with fewer 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 configuration qualifiers to the device configuration, read How Android Finds the Best-matching Resource.

Using configuration qualifiers

Android supports several configuration qualifiers that allow you to control how the system selects your alternative resources based on the characteristics of the current device screen. A configuration qualifier is a string that you can append to a resource directory in your Android project 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 the format:<resources_name>-<qualifier>
    • <resources_name> is the standard resource name (such as drawable or layout).
    • <qualifier> is a configuration qualifier from table 1, below, specifying the screen 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 each qualifier with a dash.

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

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

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

技术分享


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

For more information about how these qualifiers roughly correspond to real screen sizes and densities, seeRange of Screens Supported, earlier in this document.

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

<span class="pln" style="color:#000000;">res</span><span class="pun" style="color:#66660;">/</span><span class="pln" style="color:#000000;">layout</span><span class="pun" style="color:#66660;">/</span><span class="pln" style="color:#000000;">my_layout</span><span class="pun" style="color:#66660;">.</span><span class="pln" style="color:#000000;">xml              </span><span class="com">// layout for normal screen size ("default")</span><span class="pln" style="color:#000000;">
res</span><span class="pun" style="color:#66660;">/</span><span class="pln" style="color:#000000;">layout</span><span class="pun" style="color:#66660;">-</span><span class="pln" style="color:#000000;">large</span><span class="pun" style="color:#66660;">/</span><span class="pln" style="color:#000000;">my_layout</span><span class="pun" style="color:#66660;">.</span><span class="pln" style="color:#000000;">xml        </span><span class="com">// layout for large screen size</span><span class="pln" style="color:#000000;">
res</span><span class="pun" style="color:#66660;">/</span><span class="pln" style="color:#000000;">layout</span><span class="pun" style="color:#66660;">-</span><span class="pln" style="color:#000000;">xlarge</span><span class="pun" style="color:#66660;">/</span><span class="pln" style="color:#000000;">my_layout</span><span class="pun" style="color:#66660;">.</span><span class="pln" style="color:#000000;">xml       </span><span class="com">// layout for extra-large screen size</span><span class="pln" style="color:#000000;">
res</span><span class="pun" style="color:#66660;">/</span><span class="pln" style="color:#000000;">layout</span><span class="pun" style="color:#66660;">-</span><span class="pln" style="color:#000000;">xlarge</span><span class="pun" style="color:#66660;">-</span><span class="pln" style="color:#000000;">land</span><span class="pun" style="color:#66660;">/</span><span class="pln" style="color:#000000;">my_layout</span><span class="pun" style="color:#66660;">.</span><span class="pln" style="color:#000000;">xml  </span><span class="com">// layout for extra-large in landscape orientation</span><span class="pln" style="color:#000000;">

res</span><span class="pun" style="color:#66660;">/</span><span class="pln" style="color:#000000;">drawable</span><span class="pun" style="color:#66660;">-</span><span class="pln" style="color:#000000;">mdpi</span><span class="pun" style="color:#66660;">/</span><span class="pln" style="color:#000000;">graphic</span><span class="pun" style="color:#66660;">.</span><span class="pln" style="color:#000000;">png         </span><span class="com">// bitmap for medium-density</span><span class="pln" style="color:#000000;">
res</span><span class="pun" style="color:#66660;">/</span><span class="pln" style="color:#000000;">drawable</span><span class="pun" style="color:#66660;">-</span><span class="pln" style="color:#000000;">hdpi</span><span class="pun" style="color:#66660;">/</span><span class="pln" style="color:#000000;">graphic</span><span class="pun" style="color:#66660;">.</span><span class="pln" style="color:#000000;">png         </span><span class="com">// bitmap for high-density</span><span class="pln" style="color:#000000;">
res</span><span class="pun" style="color:#66660;">/</span><span class="pln" style="color:#000000;">drawable</span><span class="pun" style="color:#66660;">-</span><span class="pln" style="color:#000000;">xhdpi</span><span class="pun" style="color:#66660;">/</span><span class="pln" style="color:#000000;">graphic</span><span class="pun" style="color:#66660;">.</span><span class="pln" style="color:#000000;">png        </span><span class="com">// bitmap for extra-high-density</span><span class="pln" style="color:#000000;">
res</span><span class="pun" style="color:#66660;">/</span><span class="pln" style="color:#000000;">drawable</span><span class="pun" style="color:#66660;">-</span><span class="pln" style="color:#000000;">xxhdpi</span><span class="pun" style="color:#66660;">/</span><span class="pln" style="color:#000000;">graphic</span><span class="pun" style="color:#66660;">.</span><span class="pln" style="color:#000000;">png       </span><span class="com">// bitmap for extra-extra-high-density</span><span class="pln" style="color:#000000;">

res</span><span class="pun" style="color:#66660;">/</span><span class="pln" style="color:#000000;">mipmap</span><span class="pun" style="color:#66660;">-</span><span class="pln" style="color:#000000;">mdpi</span><span class="pun" style="color:#66660;">/</span><span class="pln" style="color:#000000;">my_icon</span><span class="pun" style="color:#66660;">.</span><span class="pln" style="color:#000000;">png         </span><span class="com">// launcher icon for medium-density</span><span class="pln" style="color:#000000;">
res</span><span class="pun" style="color:#66660;">/</span><span class="pln" style="color:#000000;">mipmap</span><span class="pun" style="color:#66660;">-</span><span class="pln" style="color:#000000;">hdpi</span><span class="pun" style="color:#66660;">/</span><span class="pln" style="color:#000000;">my_icon</span><span class="pun" style="color:#66660;">.</span><span class="pln" style="color:#000000;">png         </span><span class="com">// launcher icon for high-density</span><span class="pln" style="color:#000000;">
res</span><span class="pun" style="color:#66660;">/</span><span class="pln" style="color:#000000;">mipmap</span><span class="pun" style="color:#66660;">-</span><span class="pln" style="color:#000000;">xhdpi</span><span class="pun" style="color:#66660;">/</span><span class="pln" style="color:#000000;">my_icon</span><span class="pun" style="color:#66660;">.</span><span class="pln" style="color:#000000;">png        </span><span class="com">// launcher icon for extra-high-density</span><span class="pln" style="color:#000000;">
res</span><span class="pun" style="color:#66660;">/</span><span class="pln" style="color:#000000;">mipmap</span><span class="pun" style="color:#66660;">-</span><span class="pln" style="color:#000000;">xxhdpi</span><span class="pun" style="color:#66660;">/</span><span class="pln" style="color:#000000;">my_icon</span><span class="pun" style="color:#66660;">.</span><span class="pln" style="color:#000000;">png       </span><span class="com">// launcher icon for extra-extra-high-density</span><span class="pln" style="color:#000000;">
res</span><span class="pun" style="color:#66660;">/</span><span class="pln" style="color:#000000;">mipmap</span><span class="pun" style="color:#66660;">-</span><span class="pln" style="color:#000000;">xxxhdpi</span><span class="pun" style="color:#66660;">/</span><span class="pln" style="color:#000000;">my_icon</span><span class="pun" style="color:#66660;">.</span><span class="pln" style="color:#000000;">png      </span><span class="com">// launcher icon for extra-extra-extra-high-density</span>

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

Be aware that, when the Android system picks which resources to use at runtime, it uses certain logic to determine the "best matching" resources. That is, the qualifiers you use don‘t have to exactly match the current screen configuration in all cases in order for the system to use them. Specifically, when selecting resources based on the 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 xlarge qualifier, but the device is a normal-size screen). For more information about how the system selects resources, read How Android Finds the Best-matching Resource.

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

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 resources and 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 to provide alternative layouts and drawables, respectively.

Alternative layouts

Generally, you‘ll know whether you need alternative layouts for different screen sizes once you 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 the screen. For example, a row of buttons might not fit within the width of the screen on a small screen device. In this case you should provide an alternative layout for small screens that adjusts the size or position of the buttons.
  • When testing on an extra-large screen, you might realize that your layout doesn‘t make efficient 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 a redesigned UI that is optimized for bigger screens such as tablets.

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

  • And, when testing in the landscape orientation compared to the portrait orientation, you might notice that UI elements placed at the bottom of the screen for the portrait orientation should 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 scales the layout (such as the background image for a button), you should use Nine-Patch bitmap files. A Nine-Patch file is basically a PNG file in which you specify two-dimensional regions that are stretchable. When the system needs to scale the view in which the bitmap is used, the system stretches the Nine-Patch bitmap, but stretches only the specified regions. As such, you don‘t need to provide different drawables for different screen sizes, because the Nine-Patch bitmap can adjust to any size. You should, however, provide alternate versions of your Nine-Patch files for different screen densities.

Alternative drawables

技术分享

Figure 4. Relative sizes for bitmap drawables that support each density.

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

Note: You only need to provide density-specific drawables for bitmap 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 should put one copy in the default drawable directory (drawable/).

To create alternative bitmap drawables for different densities, you should follow the 3:4:6:8:12:16 scaling ratiobetween the six generalized densities. For example, if you have a 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, menu icons, 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 tablet layouts 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 screen sizes—in particular, 7" tablets—Android 3.2 introduces a new way to specify resources for 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 is that a 7" tablet is technically in the same group as a 5" handset (the large group). While these two devices are seemingly close to each other in size, the amount of space for an application‘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 different layouts for these two kinds of screens, Android now allows you to specify your layout resources based on the width and/or height that‘s actually available for your application‘s layout, specified in dp units.

For example, after you‘ve designed the layout you want to use for tablet-style devices, you might determine that the layout stops working well when the screen is less than 600dp wide. This threshold thus becomes the minimum size that you require for your tablet layout. As such, you can now specify that these layout resources should be used only when there is at least 600dp 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 the smallest width your layout supports once it‘s complete.

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

Using new size qualifiers

The different resource configurations that you can specify based on the space available for your layout are summarized in table 2. These new qualifiers offer you more control over the specific screen 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 are not the actual screen sizes. Rather, the sizes are for the width or height in dp units that are available to your activity‘s window. The Android system might use some of the screen for system UI (such as the system bar at the bottom of the screen or the status bar at the top), so some of the screen might not be available for your layout. Thus, the sizes you declare should be specifically about the sizes needed by your activity—the system accounts for any space used by system UI when declaring how much space it provides for your layout. Also beware that the Action Bar is considered a part of your application‘s window space, although your layout does not declare it, so it reduces the 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).

技术分享

技术分享

For more discussion about these size configuration qualifiers, see the Providing Resources document.While using these qualifiers might seem more complicated than using screen size groups, it should actually 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 between a handset-style UI and a tablet-style UI that uses multiple panes. The exact point of this switch will 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.

Configuration examples

To help you target some of your designs for different types of devices, here are some numbers 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 layout resources 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 two sets of layouts:

<span class="pln" style="color:#000000;">res</span><span class="pun" style="color:#66660;">/</span><span class="pln" style="color:#000000;">layout</span><span class="pun" style="color:#66660;">/</span><span class="pln" style="color:#000000;">main_activity</span><span class="pun" style="color:#66660;">.</span><span class="pln" style="color:#000000;">xml           </span><span class="com"># For handsets</span><span class="pln" style="color:#000000;">
res</span><span class="pun" style="color:#66660;">/</span><span class="pln" style="color:#000000;">layout</span><span class="pun" style="color:#66660;">-</span><span class="pln" style="color:#000000;">sw600dp</span><span class="pun" style="color:#66660;">/</span><span class="pln" style="color:#000000;">main_activity</span><span class="pun" style="color:#66660;">.</span><span class="pln" style="color:#000000;">xml   </span><span class="com"># For tablets</span>

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

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

<span class="pln" style="color:#000000;">res</span><span class="pun" style="color:#66660;">/</span><span class="pln" style="color:#000000;">layout</span><span class="pun" style="color:#66660;">/</span><span class="pln" style="color:#000000;">main_activity</span><span class="pun" style="color:#66660;">.</span><span class="pln" style="color:#000000;">xml           </span><span class="com"># For handsets (smaller than 600dp available width)</span><span class="pln" style="color:#000000;">
res</span><span class="pun" style="color:#66660;">/</span><span class="pln" style="color:#000000;">layout</span><span class="pun" style="color:#66660;">-</span><span class="pln" style="color:#000000;">sw600dp</span><span class="pun" style="color:#66660;">/</span><span class="pln" style="color:#000000;">main_activity</span><span class="pun" style="color:#66660;">.</span><span class="pln" style="color:#000000;">xml   </span><span class="com"># For 7” tablets (600dp wide and bigger)</span><span class="pln" style="color:#000000;">
res</span><span class="pun" style="color:#66660;">/</span><span class="pln" style="color:#000000;">layout</span><span class="pun" style="color:#66660;">-</span><span class="pln" style="color:#000000;">sw720dp</span><span class="pun" style="color:#66660;">/</span><span class="pln" style="color:#000000;">main_activity</span><span class="pun" style="color:#66660;">.</span><span class="pln" style="color:#000000;">xml   </span><span class="com"># For 10” tablets (720dp wide and bigger)</span>

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 the device‘s current orientation. Thus, usingsw<N>dp is a simple way to specify the overall screen size available for your layout by ignoring the screen‘s orientation.

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

<span class="pln" style="color:#000000;">res</span><span class="pun" style="color:#66660;">/</span><span class="pln" style="color:#000000;">layout</span><span class="pun" style="color:#66660;">/</span><span class="pln" style="color:#000000;">main_activity</span><span class="pun" style="color:#66660;">.</span><span class="pln" style="color:#000000;">xml         </span><span class="com"># For handsets (smaller than 600dp available width)</span><span class="pln" style="color:#000000;">
res</span><span class="pun" style="color:#66660;">/</span><span class="pln" style="color:#000000;">layout</span><span class="pun" style="color:#66660;">-</span><span class="pln" style="color:#000000;">w600dp</span><span class="pun" style="color:#66660;">/</span><span class="pln" style="color:#000000;">main_activity</span><span class="pun" style="color:#66660;">.</span><span class="pln" style="color:#000000;">xml  </span><span class="com"># Multi-pane (any screen with 600dp available width or more)</span>

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

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>dp qualifiers 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 you declare in your manifest file which screens your application supports.

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

android:requiresSmallestWidthDp
Specifies the minimum smallestWidth required. The smallestWidth is the shortest dimension of the 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 considered compatible with your application, the device‘s smallestWidth must be equal to or greater than this value. (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 600dp smallest available width:

<span class="tag" style="color:#0088;"><manifest</span><span class="pln" style="color:#000000;"> ... </span><span class="tag" style="color:#0088;">></span><span class="pln" style="color:#000000;">
    </span><span class="tag" style="color:#0088;"><supports-screens</span><span class="pln" style="color:#000000;"> </span><span class="atn" style="color:#882288;">android:requiresSmallestWidthDp</span><span class="pun" style="color:#66660;">=</span><span class="atv" style="color:#8800;">"600"</span><span class="pln" style="color:#000000;"> </span><span class="tag" style="color:#0088;">/></span><span class="pln" style="color:#000000;">
    ...
</span><span class="tag" style="color:#0088;"></manifest></span>

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

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

android:compatibleWidthLimitDp
This attribute allows you to enable screen compatibility mode as a user-optional feature by specifying the maximum "smallest width" that your application supports. 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. By default, screen compatibility mode is disabled and your layout is resized to fit the screen as usual, but a button is available in the system bar that allows users to toggle screen compatibility mode on and off.

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

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

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

Caution: When developing for Android 3.2 and higher, you should not use the older screen size attributes in combination with the attributes listed above. Using both the new attributes and the older size attributes might cause unexpected 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 function properly and look good on any of the generalized screen configurations supported by Android. The previous sections of this document provide information about how Android adapts your application to screen configurations and how you can customize the look of your application on different screen configurations. This section provides some additional tips and an overview of techniques that help ensure that your application scales properly for different screen configurations.

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

  1. Use wrap_contentfill_parent, or dp units when specifying dimensions 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 for views in an XML layout file, using"wrap_content""fill_parent" or dp units guarantees that the view is given an appropriate size on the current device screen.

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

Similarly, you should prefer the sp (scale-independent pixel) to define text sizes. The sp scale factor depends on a user setting and the system scales the size 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 the standard unit for expressing dimension or coordinate values. That means that the dimensions of a view 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 the current screen, but on a device with a higher density screen, the value returned might be 15. If you use pixel values in your application code to work with bitmaps that are not pre-scaled for the current screen density, you might need to scale the pixel values that you use in your code to match the un-scaled bitmap source.

If your application manipulates bitmaps or deals with pixel values at runtime, see the section below aboutAdditional Density Considerations.

3. Do not use AbsoluteLayout

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

You should instead use RelativeLayout, which uses relative positioning to lay out its child views. For instance, you can specify that a button widget should appear "to the 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 screen configuration, you may want to make adjustments to the UI on different screen sizes and provide bitmap drawables that are optimized for different densities. This essentially reiterates the information from earlier in this document.

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

<span class="pln" style="color:#000000;">res</span><span class="pun" style="color:#66660;">/</span><span class="pln" style="color:#000000;">drawable</span><span class="pun" style="color:#66660;">-</span><span class="pln" style="color:#000000;">mdpi</span><span class="pun" style="color:#66660;">/</span><span class="pln" style="color:#000000;">icon</span><span class="pun" style="color:#66660;">.</span><span class="pln" style="color:#000000;">png   </span><span class="com">//for medium-density screens</span><span class="pln" style="color:#000000;">
res</span><span class="pun" style="color:#66660;">/</span><span class="pln" style="color:#000000;">drawable</span><span class="pun" style="color:#66660;">-</span><span class="pln" style="color:#000000;">hdpi</span><span class="pun" style="color:#66660;">/</span><span class="pln" style="color:#000000;">icon</span><span class="pun" style="color:#66660;">.</span><span class="pln" style="color:#000000;">png   </span><span class="com">//for high-density screens</span>

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 medium density and will scale for other densities as appropriate.

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

Additional Density Considerations

This section describes more about how Android performs scaling for bitmap drawables on different screen densities and how you can further control how bitmaps are drawn on different densities. The information in this section shouldn‘t be important to most applications, unless you have encountered problems in your application when running on different screen densities or your application manipulates graphics.

To better understand how you can support multiple densities when manipulating graphics at runtime, you should understand that the system helps ensure the proper scale for bitmaps in the following 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-specific resources from your application and displays them without scaling. If resources are not available in the correct density, the system loads the default resources and scales them up or down as needed to match the current screen‘s density. The system assumes that default resources (those from a directory 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 the system does when resizing a bitmap to the appropriate size for the current screen density.

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

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

    <span class="pln" style="color:#000000;">res</span><span class="pun" style="color:#66660;">/</span><span class="pln" style="color:#000000;">drawable</span><span class="pun" style="color:#66660;">-</span><span class="pln" style="color:#000000;">nodpi</span><span class="pun" style="color:#66660;">/</span><span class="pln" style="color:#000000;">icon</span><span class="pun" style="color:#66660;">.</span><span class="pln" style="color:#000000;">png</span>

    When the system uses the icon.png bitmap from this folder, it does not scale it based 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 pixel dimension values at draw time. It does this to ensure that pixel-defined screen elements are still displayed 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 scaled pixel 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 the same size as a traditional HVGA screen, but it‘s running an application that has disabled pre-scaling. In this case, the system will "lie" to the application when it queries for screen dimensions, and report 320x533 (the approximate mdpi translation for the screen density). Then, when the 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 actually invalidate the region (15,15) to (150, 150). This discrepancy may cause unexpected behavior if your application directly manipulates the scaled bitmap, but this is considered a reasonable trade-off to keep the performance of applications as good as possible. If you encounter this situation, read the following section about Converting dp units to pixel units.

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

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

Scaling Bitmap objects created at runtime

技术分享

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

If your application creates an in-memory bitmap (a Bitmapobject), the system assumes that the bitmap is designed for the baseline medium-density screen, by default, and auto-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 properly account for the current device‘s screen density and specify the bitmap‘s density properties, the auto-scaling can result in scaling artifacts the same as when you don‘t provide alternative resources.

To control whether a Bitmap created at runtime is scaled or not, you can specify the density of the bitmap withsetDensity(), passing a density constant fromDisplayMetrics, 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 useBitmapFactory.Options to define properties of the bitmap as it already exists, which determine if or how the system will scale it. For example, you can use the inDensity field to define the density for which the bitmap is designed and the inScaled field to specify whether the bitmap should scale to match the current device‘s screen density.

If you set the inScaled field to false, then you disable any pre-scaling that the system may apply to the bitmap and the system will then auto-scale it at draw time. Using auto-scaling instead of pre-scaling can be more CPU expensive, but uses less 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 are subtle, because all of the bitmaps are being scaled to match the current screen density, however the scaled bitmaps have slightly different appearances depending on whether they are pre-scaled or auto-scaled at draw time.

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

Converting dp units to pixel units

In some cases, you will need to express dimensions in dp and then convert them to pixels. Imagine an application in which a scroll or fling gesture is recognized after the user‘s finger 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 device with a high-density display (240dpi), the user‘s must move by 16 pixels / 240 dpi, which equals 1/15th of an inch (or 1.7 mm). The distance is much shorter and the application thus appears more sensitive to the user.

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

<span class="com">// The gesture threshold expressed in dp</span><span class="pln" style="color:#000000;">
</span><span class="kwd" style="color:#0088;">private</span><span class="pln" style="color:#000000;"> </span><span class="kwd" style="color:#0088;">static</span><span class="pln" style="color:#000000;"> </span><span class="kwd" style="color:#0088;">final</span><span class="pln" style="color:#000000;"> </span><span class="kwd" style="color:#0088;">float</span><span class="pln" style="color:#000000;"> GESTURE_THRESHOLD_DP </span><span class="pun" style="color:#66660;">=</span><span class="pln" style="color:#000000;"> </span><span class="lit" style="color:#06666;">16.0f</span><span class="pun" style="color:#66660;">;</span><span class="pln" style="color:#000000;">

</span><span class="com">// Get the screen's density scale</span><span class="pln" style="color:#000000;">
</span><span class="kwd" style="color:#0088;">final</span><span class="pln" style="color:#000000;"> </span><span class="kwd" style="color:#0088;">float</span><span class="pln" style="color:#000000;"> scale </span><span class="pun" style="color:#66660;">=</span><span class="pln" style="color:#000000;"> </span><code style=""><a target=_blank target="_blank" href="http://developer.android.com/reference/android/content/ContextWrapper.html#getResources%28%29" style="color:rgb(3,155,229); text-decoration:none"><span class="pln" style="color:#000000;">getResources</span><span class="pun" style="color:#66660;">()</span></a></code><span class="pun" style="color:#66660;">.</span><code style=""><a target=_blank target="_blank" href="http://developer.android.com/reference/android/content/res/Resources.html#getDisplayMetrics%28%29" style="color:rgb(3,155,229); text-decoration:none"><span class="pln" style="color:#000000;">getDisplayMetrics</span><span class="pun" style="color:#66660;">()</span></a></code><span class="pun" style="color:#66660;">.</span><span class="pln" style="color:#000000;">density</span><span class="pun" style="color:#66660;">;</span><span class="pln" style="color:#000000;">
</span><span class="com">// Convert the dps to pixels, based on density scale</span><span class="pln" style="color:#000000;">
mGestureThreshold </span><span class="pun" style="color:#66660;">=</span><span class="pln" style="color:#000000;"> </span><span class="pun" style="color:#66660;">(</span><span class="kwd" style="color:#0088;">int</span><span class="pun" style="color:#66660;">)</span><span class="pln" style="color:#000000;"> </span><span class="pun" style="color:#66660;">(</span><span class="pln" style="color:#000000;">GESTURE_THRESHOLD_DP </span><span class="pun" style="color:#66660;">*</span><span class="pln" style="color:#000000;"> scale </span><span class="pun" style="color:#66660;">+</span><span class="pln" style="color:#000000;"> </span><span class="lit" style="color:#06666;">0.5f</span><span class="pun" style="color:#66660;">);</span><span class="pln" style="color:#000000;">

</span><span class="com">// Use mGestureThreshold as a distance in pixels...</span>

The DisplayMetrics.density field specifies the scale factor you must use to convert dp units to pixels, according to the current screen density. On a medium-density screen, DisplayMetrics.density equals 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 multiply the 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 more information, refer to the DisplayMetrics class.

However, instead of defining an arbitrary threshold for this kind of event, you should use 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, the distance in pixels used by the framework as the scroll threshold can be obtained with getScaledTouchSlop():

<span class="kwd" style="color:#0088;">private</span><span class="pln" style="color:#000000;"> </span><span class="kwd" style="color:#0088;">static</span><span class="pln" style="color:#000000;"> </span><span class="kwd" style="color:#0088;">final</span><span class="pln" style="color:#000000;"> </span><span class="kwd" style="color:#0088;">int</span><span class="pln" style="color:#000000;"> GESTURE_THRESHOLD_DP </span><span class="pun" style="color:#66660;">=</span><span class="pln" style="color:#000000;"> </span><span class="typ" style="color:#66066;">ViewConfiguration</span><span class="pun" style="color:#66660;">.</span><span class="kwd" style="color:#0088;">get</span><span class="pun" style="color:#66660;">(</span><span class="pln" style="color:#000000;">myContext</span><span class="pun" style="color:#66660;">).</span><span class="pln" style="color:#000000;">getScaledTouchSlop</span><span class="pun" style="color:#66660;">();</span>

Methods in ViewConfiguration starting with the getScaled prefix are guaranteed to return a value in pixels that will display properly regardless of the current screen 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 screen sizes and densities. The Android SDK includes emulator skins you can use, which replicate the sizes and densities of common screen configurations on which your application is likely to run. You can also modify the default size, density, and resolution of the emulator skins to replicate the characteristics of any specific screen. Using the emulator skins and additional custom configurations allows you to test any possible screen configuration, so you don‘t have 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 a series of AVDs (Android Virtual Devices), using emulator skins and screen configurations that emulate the screen sizes and densities you want your application to support. To do so, you can use the 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 from the <sdk>/tools/ directory (on all platforms). Figure 6 shows the AVD Manager 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 use to emulate some of the most common screen configurations.

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

Table 3. Various screen configurations available from emulator skins in the Android SDK (indicated in bold) and other representative resolutions.

  Low density (120), ldpi Medium density (160), mdpi High density (240), hdpi Extra-high-density (320), xhdpi
Smallscreen QVGA (240x320)   480x640  
Normalscreen WQVGA400 (240x400) 
WQVGA432 (240x432)
HVGA (320x480) WVGA800 (480x800) 
WVGA854 (480x854)
 
600x1024
640x960
Largescreen WVGA800** (480x800) 
WVGA854** (480x854)
WVGA800* (480x800) 
WVGA854* (480x854)
 
600x1024
   
Extra-Largescreen 1024x600 WXGA (1280x800)?
1024x768
1280x768
1536x1152
1920x1152 
1920x1200
2048x1536
2560x1536 
2560x1600
* To emulate this configuration, specify a custom 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 that uses 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, see the Screen Sizes and Densities dashboard.

技术分享

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

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

If you would like to test your application on a screen that uses a resolution or density not supported by the built-in skins, you can create an AVD that uses a custom resolution or 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 for the emulator with the -scale option. For example:

<span class="pln" style="color:#000000;">emulator </span><span class="pun" style="color:#66660;">-</span><span class="pln" style="color:#000000;">avd </span><span class="str" style="color:#8800;"><avd_name></span><span class="pln" style="color:#000000;"> </span><span class="pun" style="color:#66660;">-</span><span class="pln" style="color:#000000;">scale </span><span class="lit" style="color:#06666;">96dpi</span>

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

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

Android 适配不同分辨率屏幕

标签:

原文地址:http://blog.csdn.net/lin00kun11/article/details/51277179

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!