android 写布局基本小技巧

 

 http://developer.android.com/guide/practices/screens_support.html#screen-independence 这个页面里边。

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_content, fill_parent, or dp units when specifying dimensions in an XML layout file 在布局中使用wrap fill(match)和dp单位
  2. Do not use hard coded pixel values in your application code 不要使用写死的像素值
  3. Do not use AbsoluteLayout (it's deprecated)不要使用AbsoluteLayout 绝对布局。
  4. Supply alternative bitmap drawables for different screen densities 多套图放在不同密度的drawable文件夹下支持不同密度的屏幕

The following sections provide more details.下边我们会详细讲解

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

在布局中使用 wrap_content, fill_parent, or the dp 单位

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.

例如 一个view宽度是100dp那么这个view在一个m(1.0密度)的屏幕上会占用100个像素点,如果这个View显示在一个h密度的屏幕上那么系统就会把这个view放大到150个像素,这样这个view就会在屏幕上占用几乎一样大小的物理空间(就是这个100dp的view在不用密度的屏幕上显示的效果就是它们对比看起来几乎一样大小(实际物理尺寸))

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.相似的 我们应该使用sp单位来定义文本的大小,sp缩放系数依赖于用户设置,系统会像缩放以dp单位定义的view一样缩放以sp单位定义的文本。

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.

考虑到运行方面的原因和保持代码简单,安卓系统使用像素作为标准单位来显示空间坐标尺寸,这样就意味着基于当前屏幕密度view的尺寸都是由像素表示(翻译的不好)。举例来说 如果 myView.getWidth() 返回 10 那么这个view在当前设备就是10像素宽 但是在一个屏幕密度高的设备上这个值(myView.getWidth())就可能返回15了。所以如果我们在代码里写死以像素为单位的值那么系统就不会为我们自动预缩放这些view的尺寸了。

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

和其他的布局空间不太一样 绝对布局强制使用固定位置来放置他的子view们,这样在不同屏幕下 就会显示的很不协调难看,绝对布局在1.5版本就已经过时了。

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.

我们应该使用相对布局 相对布局会使用相对的位置来放置其子view。

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.

使用 size 和 特定密度的资源

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:

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

Note: If a density qualifier is not defined in a directory name, the system assumes that the resources in that directory are designed for the baseline 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.

这一部分更多的描述了Android系统是怎么样在不同屏幕密度的设备上针对不同drawable文件夹的bitmap进行缩放并且我们怎么进一步控制这些bitmap的在不同屏幕设备上的绘制。这部分的知识对于程序来说不是那么重要除非你在开发中遇到了屏幕适配的问题。

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:

    res/drawable-nodpi/icon.png

    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, from ApiDemos.

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 use BitmapFactory.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. You can find the source code for this sample application, which demonstrates using pre-scaled and auto-scaled bitmaps, inApiDemos.

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:

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

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

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

The DisplayMetrics.density field specifies the 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 withgetScaledTouchSlop():

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

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), ldpiMedium density (160), mdpiHigh density (240), hdpiExtra 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:

emulator -avd <avd_name> -scale 96dpi

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

 

第二课

Distributing to Specific Screens

QUICKVIEW

  • If necessary, you can control distribution of your application based on the device screen configuration

IN THIS DOCUMENT

  1. Declaring an App is Only for Handsets
  2. Declaring an App is Only for Tablets
  3. Publishing Multiple APKs for Different Screens

SEE ALSO

  1. Supporting Multiple Screens
  2. Optimizing Apps for Android 3.0

Although we recommend that you design your application to function properly on multiple configurations of screen size and density, you can instead choose to limit the distribution of your application to certain types of screens, such as only tablets and other large devices or only handsets and similar-sized devices. To do so, you can enable filtering by external services such as Google Play by adding elements to your manifest file that specify the screen configurations your application supports.

However, before you decide to restrict your application to certain screen configurations, you should understand the techniques forsupporting multiple screens and implement them to the best of your ability. By supporting multiple screens, your application can be made available to the greatest number of users with different devices, using a single APK.

Declaring an App is Only for Handsets


Because the system generally scales applications to fit larger screens well, you shouldn't need to filter your application from larger screens. As long as you follow the Best Practices for Screen Independence, your application should work well on larger screens such as tablets. However, you might discover that your application can't scale up well or perhaps you've decided to publish two versions of your application for different screen configurations. In such a case, you can use the <compatible-screens> element to manage the distribution of your application based on combinations of screen size and density. External services such as Google Play use this information to apply filtering to your application, so that only devices that have a screen configuration with which you declare compatibility can download your application.

The <compatible-screens> element must contain one or more <screen> elements. Each <screen> element specifies a screen configuration with which your application is compatible, using both the android:screenSizeand android:screenDensity attributes. Each <screen> element must include both attributes to specify an individual screen configuration—if either attribute is missing, then the element is invalid (external services such as Google Play will ignore it).

For example, if your application is compatible with only small and normal size screens, regardless of screen density, you must specify eight different <screen> elements, because each screen size has four density configurations. You must declare each one of these; any combination of size and density that you do not specify is considered a screen configuration with which your application is not compatible. Here's what the manifest entry looks like if your application is compatible with only small and normal screen sizes:

<manifest ... >

   
<compatible-screens>
       
<!-- all small size screens -->
       
<screenandroid:screenSize="small"android:screenDensity="ldpi"/>
       
<screenandroid:screenSize="small"android:screenDensity="mdpi"/>
       
<screenandroid:screenSize="small"android:screenDensity="hdpi"/>
       
<screenandroid:screenSize="small"android:screenDensity="xhdpi"/>
       
<!-- all normal size screens -->
       
<screenandroid:screenSize="normal"android:screenDensity="ldpi"/>
       
<screenandroid:screenSize="normal"android:screenDensity="mdpi"/>
       
<screenandroid:screenSize="normal"android:screenDensity="hdpi"/>
       
<screenandroid:screenSize="normal"android:screenDensity="xhdpi"/>
   
</compatible-screens>
    ...
   
<application ... >
        ...
   
<application>
</manifest>

Note: Although you can also use the <compatible-screens> element for the reverse scenario (when your application is not compatible with smaller screens), it's easier if you instead use the <supports-screens> as discussed in the next section, because it doesn't require you to specify each screen density your application supports.

Declaring an App is Only for Tablets


If you don't want your app to be used on handsets (perhaps your app truly makes sense only on a large screen) or you need time to optimize it for smaller screens, you can prevent small-screen devices from downloading your app by using the <supports-screens> manifest element.

For example, if you want your application to be available only to tablet devices, you can declare the element in your manifest like this:

<manifest ... >

   
<supports-screensandroid:smallScreens="false"
                     
android:normalScreens="false"
                     
android:largeScreens="true"
                     
android:xlargeScreens="true"
                     
android:requiresSmallestWidthDp="600"/>
    ...
   
<application ... >
        ...
   
</application>
</manifest>

This describes your app's screen-size support in two different ways:

  • It declares that the app does not support the screen sizes "small" and "normal", which are traditionally not tablets.
  • It declares that the app requires a screen size with a minimum usable area that is at least 600dp wide.

The first technique is for devices that are running Android 3.1 or older, because those devices declare their size based on generalized screen sizes. The requiresSmallestWidthDp attribute is for devices running Android 3.2 and newer, which includes the capability for apps to specify size requirements based on a minimum number of density-independent pixels available. In this example, the app declares a minimum width requirement of 600dp, which generally implies a 7"-or-greater screen.

Your size choice might be different, of course, based on how well your design works on different screen sizes; for example, if your design works well only on screens that are 9" or larger, you might require a minimum width of 720dp.

The catch is that you must compile your application against Android 3.2 or higher in order to use therequiresSmallestWidthDp attribute. Older versions don't understand this attribute and will raise a compile-time error. The safest thing to do is develop your app against the platform that matches the API level you've set forminSdkVersion. When you're making final preparations to build your release candidate, change the build target to Android 3.2 and add the requiresSmallestWidthDp attribute. Android versions older than 3.2 simply ignore that XML attribute, so there's no risk of a runtime failure.

For more information about why the "smallest width" screen size is important for supporting different screen sizes, read New Tools for Managing Screen Sizes.

Caution: If you use the <supports-screens> element for the reverse scenario (when your application is not compatible with larger screens) and set the larger screen size attributes to "false", then external services such as Google Play do not apply filtering. Your application will still be available to larger screens, but when it runs, it will not resize to fit the screen. Instead, the system will emulate a handset screen size (about 320dp x 480dp; see Screen Compatibility Mode for more information). If you want to prevent your application from being downloaded on larger screens, use <compatible-screens>, as discussed in the previous section aboutDeclaring an App is Only for Handsets.

Remember, you should strive to make your application available to as many devices as possible by applying all necessary techniques for supporting multiple screens. You should use <compatible-screens> or <supports-screens> only when you cannot provide compatibility on all screen configurations or you have decided to provide different versions of your application for different sets of screen configurations.

Publishing Multiple APKs for Different Screens


Although we recommend that you publish one APK for your application, Google Play allows you to publish multiple APKs for the same application when each APK supports a different set of screen configurations (as declared in the manifest file). For example, if you want to publish both a handset version and a tablet version of your application, but you're unable to make the same APK work for both screen sizes, you can actually publish two APKs for the same application listing. Depending on each device's screen configuration, Google Play will deliver it the APK that you've declared to support that device's screen.

Beware, however, that publishing multiple APKs for the same application is considered an advanced feature andmost applications should publish only one APK that can support a wide range of device configurations. Supporting multiple screen sizes, especially, is within reason using a single APK, as long as you follow the guide to Supporting Multiple Screens.

If you need more information about how to publish multiple APKs on Google Play, read Multiple APK Support.

第三课

Screen Compatibility Mode

Figure 1. An application running in compatibility mode on an Android 3.2 tablet.

Figure 2. The same application from figure 1, with compatibility mode disabled.

Notice: If you've developed an application for a version of Android lower than Android 3.0, but it does resize properly for larger screens such as tablets, you should disable screen compatibility mode in order to maintain the best user experience. To learn how to quickly disable the user option, jump to Disabling Screen Compatibility Mode.

Screen compatibility mode is an escape hatch for applications that are not properly designed to resize for larger screens such as tablets. Since Android 1.6, Android has supported a variety of screen sizes and does most of the work to resize application layouts so that they properly fit each screen. However, if your application does not successfully follow the guide to Supporting Multiple Screens, then it might encounter some rendering issues on larger screens. For applications with this problem, screen compatibility mode can make the application a little more usable on larger screens.

There are two versions of screen compatibility mode with slightly different behaviors:

Version 1 (Android 1.6 - 3.1)
The system draws the application's UI in a "postage stamp" window. That is, the system draws the application's layout the same as it would on a normal size handset (emulating a 320dp x 480dp screen), with a black border that fills the remaining area of the screen.

This was introduced with Android 1.6 to handle apps that were designed only for the original screen size of 320dp x 480dp. Because there are so few active devices remaining that run Android 1.5, almost all applications should be developed against Android 1.6 or greater and should not have version 1 of screen compatibility mode enabled for larger screens. This version is considered obsolete.

To disable this version of screen compatibility mode, you simply need to set android:minSdkVersion orandroid:targetSdkVersion to "4" or higher, or set android:resizeable to "true".

Version 2 (Android 3.2 and greater)
The system draws the application's layout the same as it would on a normal size handset (approximately emulating a 320dp x 480dp screen), then scales it up to fill the screen. This essentially "zooms" in on your layout to make it bigger, which will usually cause artifacts such as blurring and pixelation in your UI.

This was introduced with Android 3.2 to further assist applications on the latest tablet devices when the applications have not yet implemented techniques for Supporting Multiple Screens.

In general, large screen devices running Android 3.2 or higher allow users to enable screen compatibility mode when the application does not explicitly declare that it supports large screens in the manifest file. When this is the case, an icon (with outward-pointing arrows) appears next to the clock in the system bar, which allows the user to toggle screen compatibility mode on and off (figure 3). An application can also explicitly declare that it does not support large screens such that screen compatibility mode is always enabled and the user cannot disable it. (How to declare your application's support for large screens is discussed in the following sections.)

Figure 3. The pop up menu to toggle screen compatibility mode (currently disabled, so normal resizing occurs).

As a developer, you have control over when your application uses screen compatibility mode. The following sections describe how you can choose to disable or enable screen compatibility mode for larger screens when running Android 3.2 or higher.

Disabling Screen Compatibility Mode


If you've developed your application primarily for versions of Android lower than 3.0, but your application does resize properly for larger screens such as tablets, you should disable screen compatibility mode in order to maintain the best user experience. Otherwise, users may enable screen compatibility mode and experience your application in a less-than-ideal format.

By default, screen compatibility mode for devices running Android 3.2 and higher is offered to users as an optional feature when one of the following is true:

To completely disable the user option for screen compatibility mode and remove the icon in the system bar, you can do one of the following:

  • Easiest:

    In your manifest file, add the <supports-screens> element and specify the android:xlargeScreens attribute to"true":

    <supports-screens android:xlargeScreens="true" />
    

    That's it. This declares that your application supports all larger screen sizes, so the system will always resize your layout to fit the screen. This works regardless of what values you've set in the <uses-sdk> attributes.

  • Easy but has other effects:

    In your manifest's <uses-sdk> element, set android:targetSdkVersion to "11" or higher:

    <uses-sdk android:minSdkVersion="4" android:targetSdkVersion="11" />
    

    This declares that your application supports Android 3.0 and, thus, is designed to work on larger screens such as tablets.

    Caution: When running on Android 3.0 and greater, this also has the effect of enabling the Holographic theme for you UI, adding the Action Bar to your activities, and removing the Options Menu button in the system bar.

    If screen compatibility mode is still enabled after you change this, check your manifest's <supports-screens>and be sure that there are no attributes set "false". The best practice is to always explicitly declare your support for different screen sizes using the <supports-screens> element, so you should use this element anyway.

    For more information about updating your application to target Android 3.0 devices, read Optimizing Apps for Android 3.0.

Enabling Screen Compatibility Mode


When your application is targeting Android 3.2 (API level 13) or higher, you can affect whether compatibility mode is enabled for certain screens by using the <supports-screens> element.

Note: Screen compatibility mode is not a mode in which you should want your application to run—it causes pixelation and blurring in your UI, due to zooming. The proper way to make your application work well on large screens is to follow the guide to Supporting Multiple Screens and provide alternative layouts for different screen sizes.

By default, when you've set either android:minSdkVersion or android:targetSdkVersion to "11" or higher, screen compatibility mode is not available to users. If either of these are true and your application does not resize properly for larger screens, you can choose to enable screen compatibility mode in one of the following ways:

  • In your manifest file, add the <supports-screens> element and specify the android:compatibleWidthLimitDpattribute to "320":

     

    <supports-screens android:compatibleWidthLimitDp="320" />
    

    This indicates that the maximum "smallest screen width" for which your application is designed is 320dp. This way, any devices with their smallest side being larger than this value will offer screen compatibility mode as a user-optional feature.

    Note: Currently, screen compatibility mode only emulates handset screens with a 320dp width, so screen compatibility mode is not applied to any device if your value for android:compatibleWidthLimitDp is larger than 320.

  • If your application is functionally broken when resized for large screens and you want to force users into screen compatibility mode (rather than simply providing the option), you can use theandroid:largestWidthLimitDp attribute:
    <supports-screens android:largestWidthLimitDp="320" />
    

    This works the same as android:compatibleWidthLimitDp except it force-enables screen compatibility mode and does not allow users to disable it.

 

posted @ 2013-04-10 15:00  ITeer  阅读(376)  评论(0编辑  收藏  举报