(二)Supporting Different Devices支持不同的设备

来源:互联网 发布:f1 2015知乎 编辑:程序博客网 时间:2024/06/02 04:34

本文首次发表于依鹏CSDN博客,转载注明出处:http://blog.csdn.net/m0_37240709/article/details/77104169

Supporting Different Devices支持不同的设备

Android devices come in many shapes and sizes all around the world. With a wide range of device types, you have an opportunity to reach a huge audience with your app. In order to be as successful as possible on Android, your app needs to adapt to various device configurations. Some of the important variations that you should consider include different languages, screen sizes, and versions of the Android platform.
在世界各地,Android设备有很多不同的形状和大小。有了各种各样的设备类型,你就有机会用你的应用来吸引大量的用户。为了尽可能地在Android上取得成功,你的应用需要适应各种设备配置。您应该考虑的一些重要的变化包括不同的语言、屏幕大小和Android平台的版本。
This class teaches you how to use basic platform features that leverage alternative resources and other features so your app can provide an optimized user experience on a variety of Android-compatible devices, using a single application package (APK).
这个课程教你如何使用基本的平台特性,利用其他的资源和其他特性,这样你的应用使用一个单一的应用程序包(APK),就可以在各种android兼容的设备上提供良好的用户体验。

1、Supporting Different Languages支持不同的语言

It’s always a good practice to extract UI strings from your app code and keep them in an external file. Android makes this easy with a resources directory in each Android project.
从应用程序代码中提取UI字符串,并将它们保存在外部文件中是一种很好的做法。在每个Android项目中都有一个资源目录。
If you created your project using the Android SDK Tools (read Creating an Android Project), the tools create a res/ directory in the top level of the project. Within this res/ directory are subdirectories for various resource types. There are also a few default files such as res/values/strings.xml, which holds your string values.
如果您使用Android SDK工具创建的项目(请参阅创建一个Android项目),那么工具将在项目的顶层创建一个res/目录。在这个res/目录中是各种资源类型的子目录。还有一些默认的文件,比如res/valu/string.xml,它包含您的字符串值。

1.1、Create Locale Directories and String Files创建本地化目录和字符串文件

To add support for more languages, create additional values directories inside res/ that include a hyphen and the ISO language code at the end of the directory name. For example, values-es/ is the directory containing simple resources for the Locales with the language code "es". Android loads the appropriate resources according to the locale settings of the device at run time. For more information, see Providing Alternative Resources.
要添加对更多语言的支持,在res中创建额外的值目录,其中包括一个连字符和在目录名末尾的ISO语言代码。例如,values/是包含语言代码“es”的地区的简单资源的目录。Android在运行时根据设备的语言环境设置加载适当的资源。要获得更多信息,请参阅提供可选择的资源。
Once you’ve decided on the languages you will support, create the resource subdirectories and string resource files. For example:
一旦您决定了要支持的语言,就创建资源子目录和字符串资源文件。例如:

MyProject/
    res/
       values/
            strings.xml
       values-es/
          strings.xml
       values-fr/
          strings.xml


Add the string values for each locale into the appropriate file.
将每个地区的字符串值添加到相应的文件中。
At runtime, the Android system uses the appropriate set of string resources based on the locale currently set for the user's device.
在运行时,Android系统会根据当前用户设备设置的地区设置适当的字符串资源集。
For example, the following are some different string resource files for different languages.
例如,下面是不同语言的一些不同的字符串资源文件。

English (default locale), /values/strings.xml:
英语(默认语言环境),/values/strings.xml:
<?xml version="1.0" encoding="utf-8"?>
    <resources>
       <string name="title">My Application</string>
    <string name="hello_world">Hello World!</string>
</resources>


Spanish, /values-es/strings.xml:
西班牙语,/values-es/strings.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="title">Mi Aplicación</string>
    <string name="hello_world">Hola Mundo!</string>
</resources>


French, /values-fr/strings.xml:
法语,/values-fr/strings.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="title">Mon Application</string>
    <string name="hello_world">Bonjour le monde !</string>
</resources>


Note: You can use the locale qualifier (or any configuration qualifer) on any resource type, such as if you want to provide localized versions of your bitmap drawable. For more information, see Localization.
注意:您可以在任何资源类型上使用locale限定符(或任何配置限定符),例如,如果您想要提供位图可绘制的本地化版本。要了解更多信息,请参阅本地化。

1.2、Use the String Resources使用字符串资源

You can reference your string resources in your source code and other XML files using the resource name defined by the <string> element's name attribute.
您可以在源代码和其他XML文件中使用由元素name属性定义的资源名来引用您的字符串资源。
In your source code, you can refer to a string resource with the syntax R.string.<string_name>. There are a variety of methods that accept a string resource this way.
在您的源代码中,您可以使用语法R.string.<string_name>来引用一个字符串资源。有很多方法可以通过这种方式接受字符串资源
For example:
例如:
// Get a string resource from your app's Resources
String hello = getResources().getString(R.string.hello_world);

// Or supply a string resource to a method that requires a string
TextView textView = new TextView(this);
textView.setText(R.string.hello_world);


In other XML files, you can refer to a string resource with the syntax @string/<string_name> whenever the XML attribute accepts a string value.
在其他XML文件中,当XML属性接受字符串值时,您可以使用语法@string/<string_name>资源引用字符串资源。
For example:
例如:
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello_world" />


2、Supporting Different Screens支持不同的屏幕

Android categorizes device screens using two general properties: size and density. You should expect that your app will be installed on devices with screens that range in both size and density. As such, you should include some alternative resources that optimize your app’s appearance for different screen sizes and densities.
Android对设备屏幕进行了分类,使用了两个通用的属性:尺寸和密度。你应该期望你的应用程序会安装在大小和密度都在屏幕范围的设备上。因此,你应该在应用中加入一些优化应用程序外观的可选资源,以适应不同的屏幕尺寸和密度。
  • There are four generalized sizes: small, normal, large, xlarge.有四种普遍的尺寸:small, normal, large, xlarge
  • And four generalized densities: low (ldpi), medium (mdpi), high (hdpi), extra high (xhdpi).和四种普遍的密度:low (ldpi), medium (mdpi), high (hdpi), extra high (xhdpi)
To declare different layouts and bitmaps you'd like to use for different screens, you must place these alternative resources in separate directories, similar to how you do for different language strings.
想要在不同屏幕上使用的不同布局和位图,您必须将这些可选资源放在单独的目录中,类似于您为不同的语言字符串所做的工作。
Also be aware that the screens orientation (landscape or portrait) is considered a variation of screen size, so many apps should revise the layout to optimize the user experience in each orientation.
同样要注意的是,屏幕朝向(横向或纵向)被认为是屏幕尺寸的变化,因此许多应用程序都应该修改布局,以优化用户体验。

2.1、Create Different Layouts创建不同的布局

To optimize your user experience on different screen sizes, you should create a unique layout XML file for each screen size you want to support. Each layout should be saved into the appropriate resources directory, named with a -<screen_size> suffix. For example, a unique layout for large screens should be saved under res/layout-large/.
为了优化在不同屏幕大小上的用户体验,您应该为您想要支持的每个屏幕大小创建一个独特的布局XML文件。每个布局都应该保存到适当的资源目录中,并以一个-<screen_size>的后缀名命名。例如,对于大型屏幕的独特布局应该保存在res/layout-large/。
Note: Android automatically scales your layout in order to properly fit the screen. Thus, your layouts for different screen sizes don't need to worry about the absolute size of UI elements but instead focus on the layout structure that affects the user experience (such as the size or position of important views relative to sibling views).
注意:Android会自动缩放你的布局,以适应屏幕。因此,针对不同屏幕大小的布局不需要考虑UI元素的绝对大小,而是关注影响用户体验的布局结构(比如相对于兄弟视图的重要视图的大小或位置)。
For example, this project includes a default layout and an alternative layout for large screens:
例如,这个项目包括一个默认的布局和一个大屏幕的可选布局:
MyProject/
    res/
       layout/
          main.xml
       layout-large/
          main.xml


The file names must be exactly the same, but their contents are different in order to provide an optimized UI for the corresponding screen size.
文件名必须完全相同,但是它们的内容是不同的,以便为相应的屏幕大小提供优化的UI。
Simply reference the layout file in your app as usual:
简单地在你的应用程序中引用布局文件:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
}


The system loads the layout file from the appropriate layout directory based on screen size of the device on which your app is running. More information about how Android selects the appropriate resource is available in the Providing Resources guide.
该系统根据应用程序运行的设备的屏幕大小,从适当的布局目录中加载布局文件。有关Android如何选择适当资源的更多信息在提供参考资料指南中。
As another example, here's a project with an alternative layout for landscape orientation:
另一个例子,一个项目带有一个可供选择的横向布局:
MyProject/
    res/
       layout/
          main.xml
       layout-land/
          main.xml


By default, the layout/main.xml file is used for portrait orientation.
默认情况下, layout/main.xml文件用于竖屏。
If you want to provide a special layout for landscape, including while on large screens, then you need to use both the large and land qualifier:
如果您想为横屏提供一个特殊的布局,包括在大屏幕上,那么您需要同时使用大型和横屏限定符:
MyProject/
    res/
       layout/ # default (portrait)
          main.xml
       layout-land/ # landscape
          main.xml
       layout-large/ # large (portrait)
          main.xml
       layout-large-land/ # large landscape
          main.xml


Note: Android 3.2 and above supports an advanced method of defining screen sizes that allows you to specify resources for screen sizes based on the minimum width and height in terms of density-independent pixels. This lesson does not cover this new technique. For more information, read Designing for Multiple Screens.
注意:Android 3.2和以上支持一种高级的定义屏幕大小的方法,允许您根据最小宽度和高度以密度无关的像素来指定屏幕大小的资源。这一课没有涵盖这项新技术。要了解更多信息,请阅读多个屏幕的设计。

2.2、Create Different Bitmaps创建不同的位图

You should always provide bitmap resources that are properly scaled to each of the generalized density buckets: low, medium, high and extra-high density. This helps you achieve good graphical quality and performance on all screen densities.
您应该始终提供位图资源,这些位图资源适当地扩展到每一个通用的密度桶中:低、中、高和超高的密度。这有助于您在所有屏幕密度上实现良好的图形质量和性能。
To generate these images, you should start with your raw resource in vector format and generate the images for each density using the following size scale:
要生成这些图像,您应该从原始资源以矢量格式开始,并使用下面的大小来生成每个密度的图像。
  • xhdpi: 2.0
  • hdpi: 1.5
  • mdpi: 1.0 (baseline)
  • ldpi: 0.75
This means that if you generate a 200x200 image for xhdpi devices, you should generate the same resource in 150x150 for hdpi, 100x100 for mdpi, and 75x75 for ldpi devices.
这意味着,如果为xhdpi设备生成一个200x200图片,那么应该为hdpi生成150 x150的相同的资源,为mdpi设备提供100x100的,为ldpi设备生成75x75。
Then, place the files in the appropriate drawable resource directory:
然后,将文件放置在适当的可提取资源目录中:
MyProject/
    res/
       drawable-xhdpi/
          awesomeimage.png
       drawable-hdpi/
           awesomeimage.png
       drawable-mdpi/
           awesomeimage.png
       drawable-ldpi/
          awesomeimage.png


Any time you reference @drawable/awesomeimage, the system selects the appropriate bitmap based on the screen's density.
每当你引用@drawable/awesomeimage时,系统就会根据屏幕的密度选择适当的位图。
Note: Low-density (ldpi) resources aren’t always necessary. When you provide hdpi assets, the system scales them down by one half to properly fit ldpi screens.
注意:低密度(ldpi)资源并不总是必要的。当您提供hdpi的资产时,系统会将其缩减一半,以适当地适合ldpi的屏幕。
For more tips and guidelines about creating icon assets for your app, see the Iconography design guide.
关于为你的应用创建图标资产的更多提示和指导方针,请参见图标设计指南。

3、Supporting Different Platform Versions支持不同的平台版本

While the latest versions of Android often provide great APIs for your app, you should continue to support older versions of Android until more devices get updated. This lesson shows you how to take advantage of the latest APIs while continuing to support older versions as well.
虽然最新版的Android经常为你的应用提供很棒的api,但你应该继续支持老版本的Android,直到更多的设备被更新。这一课向您展示了如何利用最新的api,同时继续支持较老的版本。
The dashboard for Platform Versions is updated regularly to show the distribution of active devices running each version of Android, based on the number of devices that visit the Google Play Store. Generally, it’s a good practice to support about 90% of the active devices, while targeting your app to the latest version.
根据访问Google Play商店的设备数量,平台版本的指示板定期更新,以显示运行每个版本Android的活动设备的分布情况。一般来说,支持90%的活动设备是一种很好的做法,同时把你的应用程序定位到最新版本。
Tip: In order to provide the best features and functionality across several Android versions, you should use the Android Support Library in your app, which allows you to use several recent platform APIs on older versions.
提示:为了在几个Android版本中提供最好的特性和功能,你应该在你的应用中使用Android支持库,这允许你在旧版本上使用最近的几个平台api。

3.1、Specify Minimum and Target API Levels指定最低和目标API级别

The AndroidManifest.xml file describes details about your app and identifies which versions of Android it supports. Specifically, the minSdkVersion and targetSdkVersion attributes for the <uses-sdk> element identify the lowest API level with which your app is compatible and the highest API level against which you’ve designed and tested your app.
AndroidManifest.xml文件描述了您的应用程序的详细信息,并确定了它支持的Android版本。具体来说,minSdkVersion和targetSdkVersion属性可以识别应用程序兼容的最低API级别,以及针对应用程序设计和测试的最高的API级别。
For example:
例如:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" ... >
    <uses-sdk android:minSdkVersion="4" android:targetSdkVersion="15" />
       ...
</manifest>


As new versions of Android are released, some style and behaviors may change. To allow your app to take advantage of these changes and ensure that your app fits the style of each user's device, you should set the targetSdkVersion value to match the latest Android version available.
随着新版Android的发布,一些风格和行为可能会改变。为了让你的应用能够利用这些变化,并确保你的应用符合每个用户的设备风格,你应该设置targetSdkVersion值来匹配最新的Android版本。

3.2、Check System Version at Runtime在运行时检查系统版本

Android provides a unique code for each platform version in the Build constants class. Use these codes within your app to build conditions that ensure the code that depends on higher API levels is executed only when those APIs are available on the system.
Android为构建常量类中的每个平台版本提供了独特的代码。在您的应用程序中使用这些代码来构建条件,确保那些依赖于更高API级别的代码只有在系统上可用此API时才会执行。
private void setUpActionBar() {
    // Make sure we're running on Honeycomb or higher to use ActionBar APIs
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
       ActionBar actionBar = getActionBar();
       actionBar.setDisplayHomeAsUpEnabled(true);
    }
}


Note: When parsing XML resources, Android ignores XML attributes that aren’t supported by the current device. So you can safely use XML attributes that are only supported by newer versions without worrying about older versions breaking when they encounter that code. For example, if you set the targetSdkVersion="11", your app includes the ActionBar by default on Android 3.0 and higher. To then add menu items to the action bar, you need to set android:showAsAction="ifRoom" in your menu resource XML. It's safe to do this in a cross-version XML file, because the older versions of Android simply ignore the showAsAction attribute (that is, you do not need a separate version in res/menu-v11/).
注意:在解析XML资源时,Android忽略了当前设备不支持的XML属性。因此,您可以安全地使用新版本支持的XML属性,而不必担心老版本在遇到该代码时会崩溃。例如,如果你设置了targetSdkVersion=“11”,你的应用程序默认在Android 3.0和更高版本中包含了ActionBar。然后在操作栏中添加菜单项,您需要设置android:showAsAction=“ifRoom”,在您的菜单资源XML中。在跨版本的XML文件中这样做是安全的,因为老版本的Android完全忽略了showAsAction属性(也就是说,在res/menu-v/11中不需要单独的版本)。

3.3、Use Platform Styles and Themes使用平台样式和主题

Android provides user experience themes that give apps the look and feel of the underlying operating system. These themes can be applied to your app within the manifest file. By using these built in styles and themes, your app will naturally follow the latest look and feel of Android with each new release.
Android提供了用户体验主题,给应用程序提供了底层操作系统的外观和感觉。这些主题可以在manifest文件中应用到您的应用程序中。通过使用这些内置的风格和主题,你的应用将会自然地跟随Android的最新外观和感觉。

To make your activity look like a dialog box:
让你的activity看起来像一个对话框:
<activity android:theme="@android:style/Theme.Dialog">

To make your activity have a transparent background:
让你的activity有一个透明的背景:
<activity android:theme="@android:style/Theme.Translucent">

To apply your own custom theme defined in /res/values/styles.xml:
应用定义在/res/values/styles.xml文件中的自己的自定义主题:
<activity android:theme="@style/CustomTheme">

To apply a theme to your entire app (all activities), add the android:theme attribute to the <application> element:
要将主题应用于整个应用程序(所有activitie),请将android:theme属性添加到<application>元素:
<application android:theme="@style/CustomTheme">

For more about creating and using themes, read the Styles and Themes guide.
有关创建和使用主题的更多信息,请阅读样式和主题指南。

阅读全文
1 0
原创粉丝点击