android屏幕适配

来源:互联网 发布:php bootstrap 编辑:程序博客网 时间:2024/06/06 18:45

这篇文章是为部门培训准备的,可供学习使用,请不要转载。


先把精华拿到前面来

size:是指屏幕的大小

density:手机密度

orientation:屏幕的方向

dpi比例尺

3:4:6:8:12:16

图标大小

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

 

 

内容节选自google androiddeveloper,现在只能找到cache了,我结合项目中的理解进行了翻译

Android runs on a variety of devices thatoffer different screen sizes and densities. For applications, the Androidsystem provides a consistent development environment across devices and handlesmost of the work to adjust each application's user interface to the screen onwhich it is displayed. At the same time, the system provides APIs that allowyou to control your application's UI for specific screen sizes and densities,in order to optimize your UI design for different screen configurations. Forexample, you might want a UI for tablets that's different from the UI forhandsets.

Android能运行在各种屏幕大小和密度不同的设备上。对于应用程序,Android系统提供了一个跨设备一致的开发环境,并且处理大部分的工作,以调整运行在不同设备上的应用程序的用户界面。同时,系统提供的API,这些API允许您根据特定的屏幕大小和密度控制您的应用程序的用户界面,针对不同的屏幕配置优化您的UI设计。例如,您可能希望为平板创建和手持设备不同的用户界面

Although the system performs scaling andresizing to make your application work on different screens, you should makethe effort to optimize your application for different screen sizes anddensities. In doing so, you maximize the user experience for all devices andyour users believe that your application was actually designed for their devices—ratherthan simply stretched to fit the screen on their devices.

虽然系统进行缩放和调整,使你的应用程序能够在不同的屏幕上工作,但是你应该努力优化应用程序适配不同的屏幕大小和密度。在此过程中,您最大程度地优化了所有设备的用户体验,并且您的用户会相信:您的应用程序实际上是专为他们的设备设计的,而不是简单地拉伸以适应他们设备的屏幕。

Overview ofScreens Support

This section provides an overview ofAndroid's support for multiple screens, including: an introduction to the termsand concepts used in this document and in the API, a summary of the screenconfigurations that the system supports, and an overview of the API andunderlying screen-compatibility features.

这部分提供了安卓多屏幕适配的内容概述。包括:介绍了本文档和API文档中使用的术语和概念,系统支持的屏幕配置概要,以及基本的屏幕兼容功能的概述。

 

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.

实际的物理尺寸,以屏幕的对角线长度测量。

为简单起见,安卓集团所有的实际屏幕尺寸为四个广义的大小:小(small),正常(normal),大(large),和特大(extra-large)。

Screen density

屏幕密度

The quantity of pixels within a physical area of thescreen; 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.

一个屏幕的物理区域内像素的数量;通常称为DPI(每英寸点数)。例如,相比“正常”或“高”密度屏幕,一个“低”密度的屏幕在一个给定的物理区域内的像素较少。

为简单起见,安卓将所有的实际屏幕密度归纳为六个广义密度:低,中,高,超高,超超高,超超超高。

 

Orientation

方向

The orientation of the screen from the user's point ofview. This is either landscape or portrait, meaning that the screen's aspectratio is either wide or tall, respectively. Be aware that not only do differentdevices operate in different orientations by default, but the orientation canchange at runtime when the user rotates the device.

从用户的角度看到屏幕的方向。不是横着的就是竖着的,这意味着屏幕的纵横比不是宽就是高。要注意的是:不同的设备有不同的默认运行方向,在运行时,用户旋转设备可以改变运行方向

Resolution

分辨率

The total number of physical pixels on a screen. Whenadding support for multiple screens, applications do not work directly withresolution; applications should be concerned only with screen size and density,as specified by the generalized size and density groups.

屏幕上的物理像素总数。当为多个屏幕上添加适配时,应用程序不直接根据分辨率工作;应用程序应该只关注屏幕大小和密度,如广义大小和密度级的指定。

Density-independentpixel (dp)

设备独立像素(dp)

A virtual pixel unit that you should use when defining UIlayout, to express layout dimensions or position in a density-independent way.

在定义用户界面布局时,您需要使用虚拟的像素单元,以密度独立的方式去表达布局尺寸或位置。

Thedensity-independent pixel is equivalent to one physical pixel on a 160 dpiscreen, which is the baseline density assumed by the system for a"medium" density screen. At runtime, the system transparently handlesany scaling of the dp units, as necessary, based on the actual density of thescreen in use. The conversion of dp units to screen

密度无关的像素相当于160分辨率屏幕的一个物理像素,这是基线密度为“Middle”的屏幕密度的系统假设。在运行时,系统透明地处理任何DP单位的缩放,必要时,根据使用实际的屏幕密度将屏幕转换为DP单位的。

pixels issimple: px = dp * (dpi / 160). For example, on a 240 dpi screen, 1 dpequals 1.5 physical pixels. You should always use dp units when defining yourapplication's UI, to ensure proper display of your UI on screens with differentdensities.

重要公式:px = dp * (dpi / 160)

Range of screens supported

屏幕支持范围

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

安卓1.6(API 4)开始,安卓为多个屏幕的大小和密度提供支持,反映出了Android设备具有许多不同的屏幕配置。您可以使用安卓系统的功能来为每一个屏幕配置优化您的应用程序用户界面,并且,确保您的应用程序不仅布局呈现正确,而且尽可能在每个屏幕上提供最佳的用户体验。

To simplify the way that you design your user interfaces formultiple screens, Android divides the range of actual screen sizes anddensities into:

为了简化您设计多个屏幕的用户界面的方式,安卓将实际屏幕大小和密度的范围划分为以下级别:

  • A set of four generalized sizessmallnormallarge, and xlarge

四个大致的大小级别集合: smallnormallarge, and xlarge

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

注意:在Android 3.2(API Level 13)开始,这些大小分级被弃用并被一个新的技术取代,因为不利于基于可用的屏幕宽度管理屏幕尺寸。如果您正在开发安卓3.2或者更高,去看看那个文档获取更多的信息(我感觉累死在翻译中),记得不错这个新技术就是使用sw标签的分级,有兴趣可以了解一下。

  • A set of six generalized densities:

6个密度级别:

    • 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 baselineconfiguration that is a normal size and mdpi (medium) density. This baseline is based upon the screen configurationfor 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 Androidsupported).

广义的尺寸和密度的设置一个基线配置,即大小为normal和密度为MDPI。这个基线是基于屏幕配置的第一个Android设备,T-Mobile G1,具有HVGA屏幕(到Android 1.6,这是Android只支持屏幕配置)。(好吧,这就是告诉我们为什么使用那个160的原因)

Each generalized size and density spans a range of actual screensizes and densities. For example, two devices that both report a screen size of normal might have actual screen sizes and aspect ratios that are slightlydifferent when measured by hand. Similarly, two devices that report a screendensity of hdpi might have real pixeldensities that are slightly different. Android makes these differences abstractto applications, so you can provide UI designed for the generalized sizes anddensities and let the system handle any final adjustments as necessary. Figure1 illustrates how different sizes and densities are roughly categorized intothe different size and density groups.

每个广义的尺寸和密度跨越了一系列的实际屏幕尺寸和密度。例如,两个处于相同屏幕大小级别的设备,当实际测量时可能发现他们具有不同的实际屏幕尺寸和纵横比。同样,两设备都是hdpi屏幕密度可能真实像素密度稍有不同。安卓系统将这些差异化抽象为应用程序,这样你就可以为广义的大小和密度提供用户界面,并且让系统处理任何必要的调整。图1说明了不同的大小和密度是如何大致分为不同的大小和密度组。(实在抱歉,我只能找到网页快照,只有文本没有图)

As you design your UI for different screen sizes, you'll discoverthat each design requires a minimum amount of space. So, each generalizedscreen size above has an associated minimum resolution that's defined by thesystem. These minimum sizes are in "dp" units—the same units youshould use when defining your layouts—which allows the system to avoid worryingabout changes in screen density.

当你设计不同的屏幕尺寸的用户界面时,你会发现每个设计都需要一个最小的空间。因此,每一个广义的屏幕大小都有一个由系统定义的关联的最小分辨率。这些最小尺寸是以“DP”为单位的,在布局时您应当使用相同的单位,这保证系统不必担心屏幕密度变化。

  • 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 sizeswere not as well defined prior to Android 3.0, so you may encounter somedevices that are mis-classified between normal and large. These are also basedon the physical resolution of the screen, so may vary across devices—forexample a 1024x720 tablet with a system bar actually has a bit less spaceavailable to the application due to it being used by the system bar.

注意:在安卓3之前,这些最小屏幕尺寸没有被定义,所以你可能会遇到一些设备,这些设备是正常和大的,也都是基于屏幕的物理分辨率,但设备少一点的可用空间,由于被用于系统栏。例如一个具有系统栏的1024x720的平板。(可能大家一时间理解不了他想说啥啊,意思就是界定了最小尺寸后,是按照实际可用的来进行划分的,之前是拿屏幕来的,没有考虑系统栏之类的地方,上次和大家说过的要注意操作栏高度的)

To optimize your application's UI for the different screen sizes anddensities, you can provide alternativeresources for any of the generalized sizes and densities. Typically, youshould provide alternative layouts for some of the different screen sizes andalternative bitmap images for different screen densities. At runtime, thesystem uses the appropriate resources for your application, based on thegeneralized size or density of the current device screen.

为了优化应用程序的用户界面,对于不同的屏幕尺寸和密度,可以为其他的size和密度提供可替代资源。通常情况下,您应该为不同屏幕密度提供备选位图,为不同屏幕尺寸提供备选布局。在运行时,系统为您的应用程序使用适当的资源,是基于当前设备屏幕的广义大小或密度去选择的。

You do not need to provide alternative resources for everycombination of screen size and density. The system provides robustcompatibility features that can handle most of the work of rendering yourapplication on any device screen, provided that you've implemented your UIusing techniques that allow it to gracefully resize (as described in the Best Practices, below).

您不需要为屏幕大小和密度构成的不同组合提供备选资源。该系统提供了强大的兼容性功能,可以处理大部分的工作,这些工作使您的应用程序在任何设备屏幕上,应用你的用户界面使用的技术,优雅地调整布局和资源。

Note: The characteristics thatdefine a device's generalized screen size and density are independent from eachother. For example, a WVGA high-density screen is considered a normal sizescreen 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 itoffers the same resolution (the same number of pixels), the WVGA medium-densityscreen has a lower screen density, meaning that each pixel is physically largerand, thus, the entire screen is larger than the baseline (normal size) screen.

注:定义一个设备的广义屏幕大小和密度的特性是相互独立的。例如,一个WVGA高密度的屏幕是一个正常大小的屏幕,因为它的物理尺寸约为T-Mobile G1(Android的第一装置和基线屏幕配置)。另一方面,中密度的WVGA屏幕是一个大尺寸的屏幕。虽然它提供了相同的分辨率(像素数相同),其中密度的WVGA屏幕有一个较低的屏幕密度,意味着每个像素更大,因此,整个屏幕大于基线(正常大小)屏幕。

Density independence

密度独立

Your application achieves "density independence" when itpreserves the physical size (from the user's point of view) of user interfaceelements 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-densityscreen and smaller on a high-density screen. Such density-related size changescan cause problems in your application layout and usability. Figures2 and 3 show the difference between an application when it does not providedensity independence and when it does, respectively.

保持密度独立性是很重要的,因为没有它,一个界面元素(如按钮)在一个低密度的屏幕上更大,在一个高密度的屏幕更小。这种密度相关的尺寸变化会导致应用程序布局和可用性问题

The Android systemhelps your application achieve density independence in two ways:

安卓系统帮助你在两种方法下实现密度独立

  • The system scales dp units as appropriate for the current screen density

根据当前屏幕密度使用合适的dp值

  • The system scales drawable resources to the appropriate size, based on the current screen density, if necessary

根据当前的屏幕密度提供合适的图片资源

Infigure 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 ahigh-density screen. This is because although the actual screen sizes may bethe same, the high-density screen has more pixels per inch (the same amount ofpixels fit in a smaller area). In figure 3, the layout dimensions are specifiedin density-independent pixels (dp units).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 thedensity-independent pixel values down and up, respectively, to fit the screenas appropriate.

In most cases, youcan 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 to display atthe appropriate size, based on the appropriate scaling factor for the currentscreen's density.

在大多数情况下,你可以这样做确保你的应用程序实现密度独立,只需通过适当的指定布局密度无关的像素尺寸值(DP单位)或“wrap_content”。然后系统适当的调整位图以适当的大小展示,基于当前屏幕密度的缩放因子。

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

然而,位图的缩放会导致模糊或像素化的位图(说的像是马赛克效应一样),你可以在上图看到(脑补吧)。为了避免这些情况,你应该提供不同密度的位图资源。例如,你应该提供高密度的屏幕和系统高分辨率的位图将使用这些代替缩放位图中密度的屏幕设计。下面的章节将介绍如何为不同的屏幕配置提供可供选择的资源。

How to SupportMultiple Screens

如何支持多屏幕

The foundation of Android's support for multiple screens is itsability to manage the rendering of an application's layout and bitmap drawablesin an appropriate way for the current screen configuration. The system handles mostof the work to render your application properly on each screen configuration byscaling layouts to fit the screen size/density and scaling bitmap drawables forthe screen density, as appropriate. To more gracefully handle different screenconfigurations, however, you should also:

Android支持多屏幕的基础是:根据当前的屏幕配置采用适当的方式管理应用程序的布局和位图显示元素的渲染。系统处理的大部分工作使您的应用程序在每个屏幕配置下,适当的缩放布局和位图资源以适应屏幕大小/密度。但是,为了更优雅地处理不同的屏幕配置的适配,你也应该:

  • Explicitly declare in the manifest which screen sizes your application supports

在清单中明确声明您的应用程序支持的屏幕大小(设计人员就不要知道这些了)

By declaring which screen sizes yourapplication supports, you can ensure that only devices with the screens yousupport can download your application. Declaring support for different screensizes 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 yourapplication supports, you should include the <supports-screens> element in yourmanifest file.

为了声明您的应用的屏幕尺寸支持,您需要在清单文件中引入<supports-screens>节点

  • Provide different layouts for different screen sizes

为不同的屏幕尺寸提供不同的布局

By default, Android resizes yourapplication 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 fordifferent screen sizes. For example, on a larger screen, you might want toadjust the position and size of some elements to take advantage of theadditional screen space, or on a smaller screen, you might need to adjust sizesso that everything can fit on the screen.

默认情况下,Android系统调整应用程序的布局以适应当前设备的屏幕。在大多数情况下,这些工作都很出色。但在一些情况下,您的用户界面可能不好,可能需要不同的屏幕大小调整。例如,在大屏幕上,你可能要调整某些元素的位置和大小,以利用附加的屏幕空间,或者在一个较小的屏幕上,你可能需要调整大小让一切元素都适应屏幕。

The configuration qualifiers you canuse to provide size-specific resources are smallnormallarge, and xlarge. For example, layouts for anextra-large screen should go in layout-xlarge/.

这个说的就是把备选资源放到对应的文件夹中。

Beginning with Android 3.2 (API level13), the above size groups are deprecated and you should instead use the sw<N>dp configurationqualifier to define the smallest available width required by your layoutresources. For example, if your multi-pane tablet layout requires at least600dp of screen width, you should place it in layout-sw600dp/. Using the newtechniques for declaring layout resources is discussed further in the sectionabout Declaring Tablet Layouts for Android 3.2.

在Android 3.2(API Level 13)开始,以上尺寸组已被弃用,你应该使用SW <n> DP配置修饰符来定义布局所需资源的最小可用宽度。例如,如果你的多窗格平板布局要求至少为600dp屏幕宽度,你应该把它置于文件夹:layout-sw600dp /。更详细的东西将在那个蓝色字的章节中讨论

  • Provide different bitmap drawables for different screen densities

为不同的屏幕密度提供不同的位图资源

By default, Android scales your bitmapdrawables (.png.jpg, and .gif files) andNine-Patch drawables (.9.png files) so thatthey render at the appropriate physical size on each device. For example, ifyour application provides bitmap drawables only for the baseline, medium screendensity (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 causeartifacts in the bitmaps. To ensure your bitmaps look their best, you shouldinclude alternative versions at different resolutions for different screendensities.

默认情况下,Android缩放这些位图图片(PNG//官方最推荐的,JPG,和GIF文件//gif官方真的不推荐)和.9文件(.9.png文件//一个特殊的png,具有拉伸区域和不变区域)让他们在每个设备上呈现相应的物理尺寸。例如,如果您的应用程序仅提供基线位图图片,中等屏幕密度(MDPI),然后系统的scale,他们在一个高密度的屏幕被放大,在低密度的屏幕上被缩小。缩放会使得位图产生偏差。确保你的位图得到最佳的视觉效果,你应该为不同的屏幕密度提供不同分辨率的替代版本。

The configuration qualifiers (described indetail below) that you can 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, bitmaps for high-density screens should go in drawable-hdpi/.

你可以为特定密度资源使用的配置(在下面详细描述):ldpi(低),MDPI(中等),hdpi(高),xhdpi(特高),xxhdpi(特特高),和xxxhdpi(特特特高)。例如,高密度的屏幕位图应该置于drawablehdpi /。

Note: The mipmap-xxxhdpi qualifier isnecessary only to provide a launcher icon that can appear larger than usual onan xxhdpi device. You do not need to provide xxxhdpi assets for all your app'simages.

注:mipmap xxxhdpi限定只能提供一个启动图标,在xxhdpi设备上会比平时大。你不需要为你的应用程序的图像提供了xxxhdpi资源。

Some devices scale-up the launcher iconby as much as 25%. For example, if your highest density launcher icon image isalready extra-extra-high-density, the scaling process will make it appear lesscrisp. 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.

有些设备放大的启动图标多达25%。例如,如果你的最高密度的启动图标已经是特特高的密度,缩放过程将使它显得不那么明快。所以你应该提供一个高密度的启动图标的mipmapxxxhdpi目录给系统使用,而不是放大一个小号的图标。

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

Note: Place all yourlauncher icons in the res/mipmap-[density]/ folders, ratherthan the res/drawable-[density]/ folders. TheAndroid system retains the resources in these density-specific folders, such asmipmap-xxxhdpi, regardless of the screen resolution of the device where yourapp is installed. This behavior allows launcher apps to pick the bestresolution icon for your app to display on the home screen. For moreinformation about using the mipmap folders, see Managing Projects Overview.

注:将您所有的启动图标放在 res/mipmap-[density]/ 文件夹中,而不要放在res/drawable-[density]/ 文件夹中. 安卓系统将保留在这些密度特定文件夹的资源,比如mipmap xxxhdpi,不理会安装应用程序所在设备的屏幕分辨率。这种允许可启动应用程序选择最佳分辨率图标显示在主屏幕上(为什么要说launcherapp就不要深究了,有些插件程序是可以不创建桌面图标的)。

The size and density configuration qualifiers correspond to thegeneralized sizes and densities described in Range of screens supported,above.

告诉你大小和密度配置在上面的哪一节讲过了

Note: If you're notfamiliar with configuration qualifiers and how the system uses them to applyalternative resources, read Providing Alternative Resources for moreinformation.

注:如果您对配置限定符和系统如何应用配置限定符来提供备选资源还不熟悉,看某某某章节获得更多信息。

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

在运行时,系统对任意的资源应用以下的处理,以确保尽可能优质的在当前屏幕上展现。

1.     Thesystem uses the appropriate alternative resource

系统使用最合适的备选资源

Based on the size and density of thecurrent screen, the system uses any size- and density-specific resourceprovided in your application. For example, if the device has a high-densityscreen and the application requests a drawable resource, the system looks for adrawable resource directory that best matches the device configuration.Depending on the other alternative resources available, a resource directorywith the hdpi qualifier (suchas drawable-hdpi/) might be thebest match, so the system uses the drawable resource from this directory.

基于当前屏幕的尺寸和密度级别,系统使用您在应用中提供的尺寸、密度定制资源。例如:如果设备是高密度的,当应用需要使用图片资源时,系统会查询目录找到最适配置。相对其他可获得的备选资源,以hdpi修饰的资源目录(例如 drawable-hdpi)可能是最适合的,所以系统使用这个目录下的图片资源

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

如果没有最适资源可取,系统将会使用默认资源,按照当前屏幕尺寸、密度的需求进行放大缩小来适配。

The "default" resources arethose that are not tagged with a configuration qualifier. For example, theresources in drawable/ are the defaultdrawable resources. The system assumes that default resources are designed forthe baseline screen size and density, which is a normal screen size and amedium-density. As such, the system scales default density resources up forhigh-density screens and down for low-density screens, as appropriate.

默认的资源是那些没有使用配置修饰符标记的,例如在drawable目录下的资源就是默认资源,系统认为这些默认资源是为基线尺寸、密度所设计的,即normalsize和medium 密度。因此,系统会合适的将默认资源在高密度的屏幕上放大,在低密度的屏幕上缩小。

However, when the system is looking fora density-specific resource and does not find it in the density-specificdirectory, it won't always use the default resources. The system may insteaduse one of the other density-specific resources in order to provide betterresults when scaling. For example, when looking for a low-density resource andit is not available, the system prefers to scale-down the high-density versionof the resource, because the system can easily scale a high-density resourcedown to low-density by a factor of 0.5, with fewer artifacts, compared toscaling a medium-density resource by a factor of 0.75.

但是,当系统在寻找并且没有找到特定密度资源时,系统并不是一味的使用默认资源。系统可能使用其他密度特定的资源,以期获得最佳的缩放效果。例如,在寻找低密度资源时,然而并没有找到,系统更希望缩小一个高密度使用的资源,因为系统可以更轻易的将高密度的转变为低密度的,乘因子0.5,相比于使用中等密度的乘0.75

For more information about how Android selects alternativeresources by matching configuration qualifiers to the device configuration,read How Android Finds the Best-matching Resource.

Usingconfiguration qualifiers

Android supports several configuration qualifiers that allow youto control how the system selects your alternative resources based on thecharacteristics of the current device screen. A configuration qualifier is astring that you can append to a resource directory in your Android project andspecifies the configuration for which the resources inside are designed.

Android支持多种配置修饰符,这是配置修饰符允许你控制系统如何基于当前设备的屏幕选择你的替代资源。配置限定符是一个字符串,您可以在您的安卓项目中添加一个资源目录,并指定设计中的资源的配置。

To use a configuration qualifier:

使用配置限定符

1.     Createa new directory in your project's res/ directory andname it using the format: <resources_name>-<qualifier>

在工程中创建一个新的目录,按照这样的格式命名:<resources_name>-<qualifier>

o    <resources_name> is the standardresource name (such as drawable or layout).

<…>是标准的资源名称(例如图片drawable或布局layout)

o    <qualifier> is aconfiguration qualifier from table 1, below, specifying the screenconfiguration for which these resources are to be used (such as hdpi or xlarge).

限定符参照表一。。。

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

你可以一次使用超过一个的限定符,简单的使用-来分割每个限定符

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

将对应的资源放到对应的目录里面去,注意资源文件的命名和默认文件夹中的是一致的。

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

例如:xlarge是为特大屏幕准备的配置限定符,当你添加这个字符串到目录名中时,(例如 layout-xlarge),这暗示系统这些资源是在特大屏幕上使用的。

Table 1. Configurationqualifiers that allow you to provide special resources for different screenconfigurations.

表1,你能够为不同的屏幕配置提供特定资源而使用的配置限定符。

Screen characteristic

Qualifier

Description

翻译

Size

small

Resources for small size screens.

为小屏幕准备的资源

normal

Resources for normal size screens. (This is the baseline size.)

为通常大小的屏幕准备的资源(也是基线大小)

large

Resources for large size screens.

为大屏幕准备的资源

xlarge

Resources for extra-large size screens.

为特大屏幕准备的资源

Density

ldpi

Resources for low-density (ldpi) screens (~120dpi).

为低密度准备的资源,(0-120dpi),这里的dpi即我们上期提到的ppi下文若无必要,不在单独解释

mdpi

Resources for medium-density (mdpi) screens (~160dpi). (This is the baseline density.)

为mdpi准备的资源(也是基线密度)120-160

hdpi

Resources for high-density (hdpi) screens (~240dpi).

为高密度准备的资源(160-240dpi)

xhdpi

Resources for extra-high-density (xhdpi) screens (~320dpi).

为特高密度准备的资源(240-320dpi)

xxhdpi

Resources for extra-extra-high-density (xxhdpi) screens (~480dpi).

为特特高密度准备的资源(320-480dpi)

xxxhdpi

Resources for extra-extra-extra-high-density (xxxhdpi) uses (~640dpi). Use this for the launcher icon only, see note above.

为特特特高密度准备的资源(480-640dpi)仅用于启动图标

nodpi

Resources for all densities. These are density-independent resources. The system does not scale resources tagged with this qualifier, regardless of the current screen's density.

所有密度的资源。这些都是密度独立的资源。系统不使用此限定符标记资源,不管当前屏幕的密度。

tvdpi

Resources for screens somewhere between mdpi and hdpi; approximately 213dpi. This is not considered a "primary" density group. It is mostly intended for televisions and most apps shouldn't need it—providing mdpi and hdpi resources is sufficient for most apps and the system will scale them as appropriate. If you find it necessary to provide tvdpi resources, you should size them at a factor of 1.33*mdpi. For example, a 100px x 100px image for mdpi screens should be 133px x 133px for tvdpi.

这个是给电视特制的,不要多管

Orientation

land

Resources for screens in the landscape orientation (wide aspect ratio).

横向

port

Resources for screens in the portrait orientation (tall aspect ratio).

纵向

Aspect ratio

long

Resources for screens that have a significantly taller or wider aspect ratio (when in portrait or landscape orientation, respectively) than the baseline screen configuration.

 

notlong

Resources for use screens that have an aspect ratio that is similar to the baseline screen configuration.

 

Note: If you'redeveloping your application for Android 3.2 and higher, see the section about Declaring Tablet Layouts for Android 3.2 for informationabout new configuration qualifiers that you should use when declaring layoutresources for specific screen sizes (instead of using the size qualifiers intable 1).

注:如果你在android3.2及更高版本上开发应用,看看这些东西。

For more information about how these qualifiers roughly correspondto real screen sizes and densities, see Range of Screens Supported,earlier in this document.

For example, the following application resource directoriesprovide different layout designs for different screen sizes and differentdrawables. 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 acomplete list of configuration qualifiers (not just for screen configurations),see Providing Alternative Resources.

Be aware that, when the Android system picks which resources touse at runtime, it uses certain logic to determine the "bestmatching" resources. That is, the qualifiers you use don't have to exactlymatch 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 will use resources designed for a screen smaller than the currentscreen if there are no resources that better match (for example, a large-sizescreen will use normal-size screen resources if necessary). However, if theonly available resources are larger than the current screen, the system willnot use them and your application will crash if no other resources match thedevice 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 systemselects resources, read How Android Finds the Best-matching Resource.

要注意,当安卓系统在运行时选择使用哪个资源时,它会使用某种逻辑来确定“最佳匹配”资源。意味着,你不需要为当前屏幕的配置可能出现的所有情况都使用限定符供系统使用。具体来说,基于大小限定符选择资源时,如果没有找到相应的,系统会使用低一级的资源来适配(例如,一个大型屏幕将在必要时使用正常大小的屏幕资源)。然而,如果唯一可用的资源大于当前屏幕级别,系统不会使用它们,你的应用将因为找不到资源而崩溃(例如,如果所有的布局资源用xlarge修饰符标注,但设备是正常大小的屏幕)。有关该系统如何选择资源的更多信息,请阅读。。。

Tip: If you havesome drawable resources that the system should never scale (perhaps because youperform some adjustments to the image yourself at runtime), you should placethem in a directory with the nodpi configurationqualifier. Resources with this qualifier are considered density-agnostic andthe system will not scale them.

标签:如果你有一些不希望系统缩放的图片资源,应当置于nodpi修饰的目录下,这种目录下的资源不会被缩放。

Designingalternative layouts and drawables

设计备选布局和图片资源

The types of alternative resources you should create depends onyour application's needs. Usually, you should use the size and orientationqualifiers to provide alternative layout resources and use the densityqualifiers to provide alternative bitmap drawable resources.

您应当根据您的应用过的需求来创建备选资源的类型。通常,您应当使用size和orientation限定符来提供备选布局资源,使用密度限定符来提供备选位图资源。

The following sections summarize how you might want to use thesize and density qualifiers to provide alternative layouts and drawables,respectively.

接下来的章节总结了您应当如何恰当的使用限定符以提供备选资源

Alternative layouts

备选布局

Generally, you'll know whether you need alternative layouts fordifferent screen sizes once you test your application on different screenconfigurations. 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.

当在小屏幕上测试时,您可能发现您的布局并不是很贴合屏幕,例如:一行button可能在小屏幕手机上超出了屏幕宽度。这种情况下,您需要为小屏幕设备提供备选布局来调整按钮的大小和位置。

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

当在特大屏幕上测试时,你可能意识到您的布局没有有效的利用大屏幕而且没有明显的拉伸来填充屏幕。在这种情况下,您应当提供备选布局来提供为大屏幕设备(如平板)特制的UI。

Although your application should workfine without an alternative layout on big screens, it's quite important tousers that your application looks as though it's designed specifically fortheir devices. If the UI is obviously stretched, users are more likely to beunsatisfied 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.

同时,当在测试横向和纵向切换时,您可能注意到(一个注意到用了三个不同的词汇,呃,这不是写作指导,哈哈)UI元素在纵向时应当置于底部而在横向时应当置于屏幕的右侧。

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 evenafter the system scales the 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-dimensionalregions that are stretchable. When the system needs to scale the view in whichthe bitmap is used, the system stretches the Nine-Patch bitmap, but stretchesonly the specified regions. As such, you don't need to provide differentdrawables for different screen sizes, because the Nine-Patch bitmap can adjustto any size. You should, however, provide alternate versions of your Nine-Patchfiles for different screen densities.

如果您的UI使用了需要在系统缩放布局后仍然需要适应视图大小的位图(例如按钮的背景图片),您应当使用.9图片,.9图片基本上是一个PNG文件,在您指定的二维区域具有伸缩性。。。(.9图片以后找机会再和大家讨论,这种图片缩放技术是一种很强大的适配技术,简单的几句话很难讲明白)

Alternative drawables

备选图片

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

几乎每一个应用程序应该为不同屏幕密度准备备选图片资源,因为几乎每个应用程序都有一个启动图标,图标应该在所有屏幕密度看起来一致。同样的,如果你在你的应用程序中使用其他位图资源(如菜单图标或应用程序中的其它图形),你应该为不同密度提供替代版本或单独的文件。

Note: You only needto provide density-specific drawables for bitmap files (.png.jpg, or .gif) andNine-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/).

note:您只需要为位图文件提供密度特制图片资源,如果您使用了xml文件去定义形状,颜色(颜色有这个需求吗?颜色还区分屏幕大小,也是够了)或者其他的资源,您需要在默认文件中留一份备份

To create alternative bitmap drawables for different densities,you should follow the 3:4:6:8:12:16scaling ratio between the sixgeneralized densities. For example, if you have a bitmap drawable that's 48x48pixels for medium-density screens, all the different sizes should be:

上次说到的比例,好像上次我说的icon图片有两个算错了

  • 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 launchericons, menu icons, status bar icons, tab icons, and more.

//************************************************

//后面的内容是扩展部分,就不翻译了

//************************************************

DeclaringTablet Layouts for Android 3.2

//这部分是平板的,如果没有特殊需求,我们不涉及平板,就先不翻译了

For the first generation of tablets running Android 3.0, theproper way to declare tablet layouts was to put them in a directory with the xlarge configurationqualifier (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 morediscrete screen sizes. The new technique is based on the amount of space yourlayout needs (such as 600dp of width), rather than trying to make your layoutfit the generalized size groups (such as large or xlarge).

The reason designing for 7" tablets is tricky when using thegeneralized size groups is that a 7" tablet is technically in the samegroup as a 5" handset (the large group). While these two devices areseemingly close to each other in size, the amount of space for an application'sUI is significantly different, as is the style of user interaction. Thus, a7" and 5" screen should not always use the same layout. To make itpossible for you to provide different layouts for these two kinds of screens,Android now allows you to specify your layout resources based on the widthand/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 fortablet-style devices, you might determine that the layout stops working wellwhen the screen is less than 600dp wide. This threshold thus becomes the minimumsize that you require for your tablet layout. As such, you can now specify thatthese layout resources should be used only when there is at least 600dp ofwidth available for your application's UI.

You should either pick a width and design to it as your minimumsize, or test what is the smallest width your layout supports once it'scomplete.

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

Using newsize qualifiers

The different resource configurations that you can specify basedon the space available for your layout are summarized in table 2. These newqualifiers offer you more control over the specific screen sizes yourapplication supports, compared to the traditional screen size groups (small,normal, large, and xlarge).

Note: The sizes thatyou specify using these qualifiers are not the actual screen sizes. Rather, thesizes are for the width or height in dp units that are availableto your activity's window. The Android system might usesome of the screen for system UI (such as the system bar at the bottom of thescreen or the status bar at the top), so some of the screen might not beavailable for your layout. Thus, the sizes you declare should be specificallyabout the sizes needed by your activity—the system accounts for any space usedby system UI when declaring how much space it provides for your layout. Alsobeware that the Action Bar is considered apart of your application's window space, although your layout does not declareit, so it reduces the space available for your layout and you must account forit in your design.

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

Screen configuration

Qualifier values

Description

smallestWidth

sw<N>dp

Examples:
sw600dp
sw720dp

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

The smallestWidth of a device takes into account screen decorations and system UI. For example, if the device has some persistent UI elements on the screen that account for space along the axis of the smallestWidth, the system declares the smallestWidth to be smaller than the actual screen size, because those are screen pixels not available for your UI.

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 is often the driving factor in designing a layout. A UI will often scroll vertically, but have fairly hard constraints on the minimum space it needs horizontally. The available width is also the key factor in determining whether to use a one-pane layout for handsets or multi-pane layout for tablets. Thus, you likely care most about what the smallest possible width will be on each device.

Available screen width

w<N>dp

Examples:
w720dp
w1024dp

Specifies a minimum available width in dp units at which the resources should be used—defined by the <N> value. The system's corresponding value for the width changes when the screen's orientation switches between landscape and portrait to reflect 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 a tablet device, you often won't want the same multi-pane layout for portrait orientation as you do for landscape. Thus, you can use this to specify the minimum width required for the layout, instead of using both the screen size and orientation qualifiers together.

Available screen height

h<N>dp

Examples:
h720dp
h1024dp
etc.

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

Using this to define the height required by your layout is useful in the same way as w<N>dp is for defining 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 are thus more flexible with how much height is available, whereas the width is more rigid.

While using these qualifiers might seem more complicated thanusing screen size groups, it should actually be simpler once you determine therequirements for your UI. When you design your UI, the main thing you probablycare about is the actual size at which your application switches between ahandset-style UI and a tablet-style UI that uses multiple panes. The exact pointof this switch will depend on your particular design—maybe you need a 720dpwidth for your tablet layout, maybe 600dp is enough, or 480dp, or some numberbetween these. Using these qualifiers in table 2, you are in control of theprecise size at which your layout changes.

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

Configurationexamples

To help you targetsome of your designs for different types of devices, here are some numbers fortypical 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 sizequalifiers from table 2, your application can switch between your differentlayout resources for handsets and tablets using any number you want for widthand/or height. For example, if 600dp is the smallest available width supportedby your tablet layout, you can provide these two sets of layouts:

res/layout/main_activity.xml           # For handsets

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

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

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

res/layout/main_activity.xml           # For handsets (smaller than 600dpavailable 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 theprevious two sets of example resources use the "smallest width"qualifier, sw<N>dp, which specifiesthe smallest of the screen's two sides, regardless of the device's current orientation.Thus, using sw<N>dp is a simpleway to specify the overall screen size available for your layout by ignoringthe screen's orientation.

However, in somecases, what might be important for your layout is exactly how much width orheight is currently available. For example, if you have atwo-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 inlandscape or portrait orientation. In this case, your resources might look likethis:

res/layout/main_activity.xml         # For handsets (smaller than 600dpavailable width)

res/layout-w600dp/main_activity.xml  # Multi-pane (any screen with 600dp availablewidth or more)

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

If the available heightis 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 qualifiersif you need to be really specific.

Declaringscreen size support

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

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

android:requiresSmallestWidthDp

Specifies theminimum smallestWidth required. The smallestWidth is the shortest dimension ofthe screen space (in dp units) thatmust be available to your application UI—that is, the shortest of the availablescreen's two dimensions. So, in order for a device to be considered compatiblewith your application, the device's smallestWidth must be equal to or greaterthan this value. (Usually, the value you supply for this is the "smallestwidth" that your layout supports, regardless of the screen's currentorientation.)

For example, if your application isonly for tablet-style devices with a 600dp smallest available width:

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

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

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

android:compatibleWidthLimitDp

This attributeallows you to enable screen compatibility mode as auser-optional feature by specifying the maximum "smallest width" thatyour application supports. If the smallest side of a device's available screenis greater than your value here, users can still install your application, butare offered to run it in screen compatibility mode. By default, screencompatibility 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 togglescreen compatibility mode on and off.

Note: Ifyour application's layout properly resizes for large screens, you do not needto use this attribute. We recommend that you avoid using this attribute andinstead ensure your layout resizes for larger screens by following therecommendations in this document.

android:largestWidthLimitDp

This attributeallows you to force-enable screen compatibility mode by specifyingthe maximum "smallest width" that your application supports. If thesmallest 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 todisable it.

Note: Ifyour application's layout properly resizes for large screens, you do not needto use this attribute. We recommend that you avoid using this attribute andinstead ensure your layout resizes for larger screens by following therecommendations in this document.

Caution: When developingfor Android 3.2 and higher, you should not use the older screen size attributesin combination with the attributes listed above. Using both the new attributesand the older size attributes might cause unexpected behavior.

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

BestPractices

//示例,有兴趣的可以看看,上次零零碎碎的提到过这些东西。

The objective of supporting multiple screens is to create anapplication that can function properly and look good on any of the generalizedscreen configurations supported by Android. The previous sections of thisdocument provide information about how Android adapts your application toscreen configurations and how you can customize the look of your application ondifferent screen configurations. This section provides some additional tips andan overview of techniques that help ensure that your application scalesproperly for different screen configurations.

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

1.     Use wrap_contentfill_parent, or dp units whenspecifying dimensions in an XML layout file

2.     Donot use hard coded pixel values in your application code

3.     Donot use AbsoluteLayout (it'sdeprecated)

4.     Supplyalternative bitmap drawables for different screen densities

The following sections provide more details.

1. Usewrap_content, fill_parent, or the dp unit for layout dimensions

When defining the android:layout_width and android:layout_height for views in anXML layout file, using "wrap_content""fill_parent" or dp unitsguarantees that the view is given an appropriate size on the current devicescreen.

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

Similarly, you should prefer the sp (scale-independentpixel) to define text sizes. The sp scale factordepends on a user setting and the system scales the size the same as it doesfor dp.

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

For performance reasons and to keep the code simpler, the Androidsystem uses pixels as the standard unit for expressing dimension or coordinatevalues. That means that the dimensions of a view are always expressed in thecode using pixels, but always based on the current screen density. Forinstance, if myView.getWidth() returns 10, theview is 10 pixels wide on the current screen, but on a device with a higherdensity screen, the value returned might be 15. If you use pixel values in yourapplication code to work with bitmaps that are not pre-scaled for the currentscreen density, you might need to scale the pixel values that you use in yourcode to match the un-scaled bitmap source.

If your application manipulates bitmaps or deals with pixel valuesat runtime, see the section below about Additional Density Considerations.

3. Do notuse AbsoluteLayout

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

You should instead use RelativeLayout,which uses relative positioning to lay out its child views. For instance, youcan specify that a button widget should appear "to the right of" atext widget.

4. Use sizeand density-specific resources

Although the system scales your layout and drawable resourcesbased on the current screen configuration, you may want to make adjustments tothe UI on different screen sizes and provide bitmap drawables that areoptimized for different densities. This essentially reiterates the informationfrom earlier in this document.

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

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

Note: If a densityqualifier is not defined in a directory name, the system assumes that theresources in that directory are designed for the baseline medium density andwill scale for other densities as appropriate.

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

AdditionalDensity Considerations

This section describes more about how Android performs scaling forbitmap drawables on different screen densities and how you can further controlhow bitmaps are drawn on different densities. The information in this sectionshouldn't be important to most applications, unless you have encounteredproblems in your application when running on different screen densities or yourapplication manipulates graphics.

To better understand how you can support multiple densities whenmanipulating graphics at runtime, you should understand that the system helpsensure the proper scale for bitmaps in the following ways:

1.     Pre-scaling ofresources (such as bitmap drawables)

Based on the density of the currentscreen, the system uses any size- or density-specific resources from yourapplication and displays them without scaling. If resources are not availablein the correct density, the system loads the default resources and scales themup or down as needed to match the current screen's density. The system assumesthat default resources (those from a directory without configurationqualifiers) are designed for the baseline screen density (mdpi), unless theyare loaded from a density-specific resource directory. Pre-scaling is, thus,what the system does when resizing a bitmap to the appropriate size for thecurrent screen density.

If you request the dimensions of apre-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 to75x75 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 youmight not want Android to pre-scale a resource. The easiest way to avoidpre-scaling is to put the resource in a resource directory with the nodpiconfiguration qualifier. For example:

res/drawable-nodpi/icon.png

When the system uses the icon.png bitmapfrom this folder, it does not scale it based on the current device density.

2.     Auto-scaling ofpixel dimensions and coordinates

An application can disable pre-scalingby setting android:anyDensity to "false" in the manifestor programmatically for a Bitmap by setting inScaled to "false". In this case,the system auto-scales any absolute pixel coordinates and pixel dimensionvalues at draw time. It does this to ensure that pixel-defined screen elementsare still displayed at approximately the same physical size as they would be atthe baseline screen density (mdpi). The system handles this scalingtransparently to the application and reports the scaled pixel dimensions to theapplication, rather than physical pixel dimensions.

For instance, suppose a device has aWVGA high-density screen, which is 480x800 and about the same size as atraditional HVGA screen, but it's running an application that has disabledpre-scaling. In this case, the system will "lie" to the applicationwhen it queries for screen dimensions, and report 320x533 (the approximate mdpitranslation for the screen density). Then, when the application does drawingoperations, such as invalidating the rectangle from (10,10) to (100, 100), thesystem transforms the coordinates by scaling them the appropriate amount, andactually invalidate the region (15,15) to (150, 150). This discrepancy maycause unexpected behavior if your application directly manipulates the scaledbitmap, but this is considered a reasonable trade-off to keep the performanceof applications as good as possible. If you encounter this situation, read thefollowing 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 techniquesdescribed above in How to Support Multiple Screens.

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

ScalingBitmap objects created at runtime

If your application creates an in-memory bitmap (a Bitmap object), thesystem assumes that the bitmap is designed for the baseline medium-densityscreen, by default, and auto-scales the bitmap at draw time. The system applies"auto-scaling" to a Bitmap when the bitmaphas unspecified density properties. If you don't properly account for thecurrent 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'tprovide alternative resources.

To control whether a Bitmap created atruntime is scaled or not, you can specify the density of the bitmap with setDensity(),passing a density constant from DisplayMetrics,such as DENSITY_HIGH orDENSITY_LOW.

If you're creating a Bitmap using BitmapFactory,such as from a file or a stream, you can use BitmapFactory.Options to defineproperties of the bitmap as it already exists, which determine if or how thesystem will scale it. For example, you can use the inDensity field to definethe density for which the bitmap is designed and the inScaled field tospecify whether the bitmap should scale to match the current device's screendensity.

If you set the inScaled field to false, then you disable any pre-scaling thatthe system may apply to the bitmap and the system will then auto-scale it atdraw 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-scalemechanisms when loading low (120), medium (160) and high (240) density bitmapson a high-density screen. The differences are subtle, because all of thebitmaps are being scaled to match the current screen density, however thescaled bitmaps have slightly different appearances depending on whether theyare pre-scaled or auto-scaled at draw time.

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

Converting dpunits to pixel units

In some cases, you will need to express dimensions in dp andthen convert them to pixels. Imagine an application in which a scroll or flinggesture 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. Ona device with a high-density display (240dpi), the user's must move by 16 pixels / 240 dpi, which equals1/15th of an inch (or 1.7 mm). The distance is much shorter and the applicationthus appears more sensitive to the user.

To fix this issue, the gesture threshold must be expressed in codein dp andthen converted 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 specifiesthe scale factor you must use to convert dp units topixels, according to the current screen density. On a medium-density screen, DisplayMetrics.density equals 1.0; ona high-density screen it equals 1.5; on an extra-high-density screen, it equals2.0; and on a low-density screen, it equals 0.75. This figure is the factor bywhich you should multiply thedp units on orderto get the actual pixel count for the current screen. (Then add 0.5f toround the figure up to the nearest whole number, when converting to aninteger.) For more information, refer to the DisplayMetrics class.

However, instead of defining an arbitrary threshold for this kindof event, you should use pre-scaled configuration values that are availablefrom ViewConfiguration.

Using pre-scaled configuration values

You can use the ViewConfiguration class to accesscommon distances, speeds, and times used by the Android system. For instance,the distance in pixels used by the framework as the scroll threshold can beobtained with getScaledTouchSlop():

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

Methods in ViewConfiguration starting withthe getScaled prefix areguaranteed to return a value in pixels that will display properly regardless ofthe current screen density.

How to TestYour Application on Multiple Screens

Before publishing your application, you should thoroughly test itin all of the supported screen sizes and densities. The Android SDK includesemulator skins you can use, which replicate the sizes and densities of commonscreen configurations on which your application is likely to run. You can alsomodify the default size, density, and resolution of the emulator skins toreplicate the characteristics of any specific screen. Using the emulator skinsand additional custom configurations allows you to test any possible screenconfiguration, so you don't have to buy various devices just to test yourapplication's screen support.

To set up an environment for testing your application's screensupport, you should create a series of AVDs (Android Virtual Devices), usingemulator skins and screen configurations that emulate the screen sizes anddensities you want your application to support. To do so, you can use the AVDManager to create the AVDs and launch them with a graphical interface.

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

Table 3 shows the various emulator skins that are available in theAndroid SDK, which you can use to emulate some of the most common screenconfigurations.

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

Table 3. Various screenconfigurations available from emulator skins in the Android SDK (indicated inbold) and other representative resolutions.

Low density (120), ldpi

Medium density (160), mdpi

High density (240), hdpi

Extra-high-density (320), xhdpi

Small screen

QVGA (240x320)

480x640

Normal screen

WQVGA400 (240x400) 
WQVGA432 (240x432)

HVGA (320x480)

WVGA800 (480x800) 
WVGA854 (480x854)
 
600x1024

640x960

Large screen

WVGA800** (480x800) 
WVGA854** (480x854)

WVGA800* (480x800) 
WVGA854* (480x854)
 
600x1024

Extra-Large screen

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 anygiven screen configuration, see the Screen Sizes and Densities dashboard.

We also recommend that you test your application in an emulatorthat 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 anddensities. To do so you need to know the approximate density, in dpi, of yourcomputer monitor (for instance, a 30" Dell monitor has a density of about96 dpi). When you launch an AVD from the AVD Manager, you can specify thescreen size for the emulator and your monitor dpi in the Launch Options, asshown in figure 7.

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

If you are launching your AVD from the command line, you canspecify the scale for the emulator with the -scale option. Forexample:

emulator -avd <avd_name> -scale 96dpi

To refine the size of the emulator, you can instead pass the -scale optiona 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.

 

 

 

0 1