Android doc |Getting Started|部分 部分译文 --Supporting Different Devices

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.

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

Android设备有各种大小和形状。有这么多的设备种类,将会有更多人关注你的app。为了尽可能让你的app在Android系统成功显示,你需要适配各种各样的设备参数。你需要将这些区别考虑进设备适配中:设备的大小尺寸,语言,设备的Android版本。
这节课教你如何使用基本的平台功能让你的App在不同的设备上都能提供一个良好的用户体验(只使用一个APK)

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.

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.
抽取从你的APP代码UI的字符并把它们放在一个外部文件(string.xml等等)是一个好习惯。在Android中这样做是很简单的,在每个Android项目都有一个资源目录(你可以抽取字符串放在这些资源目录中)
如果你是用Android SDK工具创建的Android项目,工具会在项目的顶层目录创建一个res/目录。在这个res/values/string.xml的文件中,会存放你的String的值。

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/创建一个额外的目录包含values加一个连字符并以ISO(国际标准化组织)语言码结尾。如:values-es/ 是为了语言码是es的区域建立的包含简单资源的目录

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.
为每个地区增加string的值到适当的文件。

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:

<?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:

<?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:

<?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
注意:你可以使用区域修饰符(或者任何参数修饰符)在任意的资源类型,比如如果你想提供一个本地化版本的图片。更多信息请参见本地化。

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文件中使用在<string> 元素中指定的资源name来指向你的字符串资源
In your source code, you can refer to a string resource with the syntax R.string.. There are a variety of methods that accept a string resource this way.
在你的源码中,你可以用以下语法找到字符串资源:R.string..这边有几种方法来接收字符串。
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文件,你可以使用以下语法获取字符串:@string/<string_name>

For example:

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello_world" />

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设备的屏幕有两个主要参数:屏幕大小和密度(像素)。你应该为你的app将安装到不同尺寸不同像素(密度)的Android设备做好打算。同样的,你应该提供可选择的资源文件来使你的app外观装在在不同的尺寸和密度的设备都能最优化

  • There are four generalized sizes: small, normal, large, xlarge
  • And four generalized densities: 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.
也要注意不同屏幕的方向(水平和垂直)变动,所以许多app应该修改布局来让每种方向都能达到良好的用户体验。

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会自动缩放你的layout。因此

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.
系统会基于运行你app的设备的屏幕尺寸加载适当目录的布局文件。关于Android系统如何选择适当的资源的更多信息在Providing Resources指南。

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:
如果你想提供一个特殊的竖屏布局,包括大屏,那么你需要同时使用large和land修饰符

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及以上版本支持定义屏幕尺寸的高级方法,可以让你根据密度独立像素方面的最小宽度和高度指定屏幕尺寸的资源。本课程不涉及这种新技术。欲了解更多信息,请阅读设计适配多屏幕。

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.
你应该为普遍的不同像素的设备(低 中 高 超高像素)提供可以适当缩放的位图资源。这会帮助提高你的app在各个像素屏幕的性能和图形质量。

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 mdpi ldpi的设备,你应该生成150x150 100x100 75x75的图片

Then, place the files in the appropriate drawable resource directory:
然后将这些图片放在合适的drawable资源目录

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的屏幕

For more tips and guidelines about creating icon assets for your app, see the Iconography design guide.
有关为你的app创建图标图片等,欲了解更多的技巧和指南 ,请参阅Iconography设计指南。

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版本往往提供更强大的APIs,但是知道更多设备更新之前,你仍然应该继续支持低版本的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.
PlatForm版本的表格会定期更新以展示活跃的设备烦人Android版本的分布(基于访问Google Play应用商店的设备数)。总之,适配90%的设备是好的吧,targeting your app to the latest version.。

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版本提供最佳的性能和功能,你应该在你的App使用Android支持类库,这个会允许你在较老版本使用最近的几个平台APIs

Specify Minimum and Target API Levels
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文件描述了你App的细节并标识app支持什么样的Android版本。具体的,<uses-sdk> 元素里面minSdkVersion和 targetSdkVersion 属性指定了app编译的最低API级别和以及最高API级别(你测试app的级别)

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发布,app的一些行为也许会变化。为了让你的app充分利用这些修改,并切在各个app使用者的设备适配这些风格,你应该设置targetSdkVersion为最新的Android版本。

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提供了在Build常量类为每个版本提供了独立的代码。在你的app使用这些代码来写条件确保代码只有当高版本的是可用的时候,高版本的代码才会执行。

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会忽略当前设备不支持的Android XML属性。所以你尽可以放心的使用只有更新版本才支持的XML属性而不用担心旧版的设备跑到这里会挂掉。举个例子,如果你设置targetSdkVersion=“11”,你的App默认包含了 Android 3.0及以上版本所支持的ActionBar。为了在action bar添加菜单选项,你需要在你的菜单资源文件中设置android:showAsAction=”ifRoom”属性。这样做在跨版本时是安全的,因为低版本的Android会直接忽略showAsAction属性(也就是说,你不需要单独建一个文件为res/menu-v11/)

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.
通过使用这些style和theme,你的app风格将跟随最新的Android Release。

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:
在整个app应用你的自定义主题,在Application元素添加android:theme属性

<application android:theme="@style/CustomTheme">

For more about creating and using themes, read the Styles and Themes guide.
更多创建和使用主题,参见Styles and Themes指南。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值