Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android doc Training部分 部分譯文 --Supporting Different Devices

Android doc Training部分 部分譯文 --Supporting Different Devices

編輯:關於Android編程

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:



    My Application
    Hello World!

Spanish, /values-es/strings.xml:



    Mi Aplicación
    Hola Mundo!

French, /values-fr/strings.xml:



    Mon Application
    Bonjour le monde !

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 element’s name attribute.
你可以在你的源碼和其他XML文件中使用在 元素中指定的資源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/ whenever the XML attribute accepts a string value.
在其他的XML文件,你可以使用以下語法獲取字符串:@string/

For example:

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 - suffix. For example, a unique layout for large screens should be saved under res/layout-large/.
為了在不同尺寸的屏幕優化你的用戶體驗,你應該為你想要支持的不同尺寸的屏幕創建單獨的XML布局文件。每個布局應該被保存進適當的資源目錄(使用- 作為後綴)。比如,一個大屏的單獨的布局應該被保存在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 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版本。具體的, 元素裡面minSdkVersion和 targetSdkVersion 屬性指定了app編譯的最低API級別和以及最高API級別(你測試app的級別)

For example:
舉例:


    
    ...

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看起來像個對話框:


To make your activity have a transparent background:
讓你的activity看起來像個透明的背景:


To apply your own custom theme defined in /res/values/styles.xml:
在/res/values/styles.xml定義主題並應用你的自定義主題:


To apply a theme to your entire app (all activities), add the android:theme attribute to the element:
在整個app應用你的自定義主題,在Application元素添加android:theme屬性


For more about creating and using themes, read the Styles and Themes guide.
更多創建和使用主題,參見Styles and Themes指南。

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved