本文介绍XamarinAndroid中的Android资源概念,以及如何使用资源。讨论如何使用资源实现应用程序本地化,多种设备支持如各种屏幕大小和密度。
This article introduces the concept of Android resourcesin Xamarin.Android and will document how to use them. It covers how to useresources in your Android application to support application localization, andmultiple devices including varying screen sizes and densities.
很少有Android应用程序只包含源码。通常还有很多组成应用程序的文件:视频、图像、音频文件等等。总体上说,非源码文件都是资源,在生成过程和打包APK的时候与源码一起编辑,并同时安装到设备:
AnAndroid application is seldom just source code. There are often many otherfiles that make up an application: video, images, and audio files just to namea few. Collectively, these non-source code files are referred to as resourcesand are compiled (along with the source code) during the build process andpackaged as an APK for distribution and installation onto devices:
资源为Android应用程序提供各种优势:
代码隔离—将代码与图像、字符、菜单、动画、颜色等隔离开。比如可以方便的本地化。
多设备部署—无需修改代码就可以简单的实现不同设备的配置支持。
编译时检查—资源是静态的,可编译到应用程序中。这样就可以在编译的时候检查资源,修正错误,否则在运行时很难定位和修改错误。
当新创建一个Xamarin Android项目,会创建一个叫做Resources的目录,同时还有很多子目录:
Resourcesoffer several advantages to an Android application:
Code-Separation -Separates source code from images, strings, menus, animations, colors, etc. Assuch resources can help considerably when localizing.
Target multiple devices – Provides simpler support of different deviceconfigurations without code changes.
Compile-time Checking - Resources are static and compiled into theapplication. This allows the usage of the resources to be checked at compiletime, when it will be easy to catch and correct the mistakes, as opposed torun-time when it is more difficult to locate and costly to correct.
When a new Xamarin.Android project is started, aspecial directory called Resources is created, along with some subdirectories:
上图所示,应用程序资源按类型组织到各个子目录中:图像放在drawable目录;控件放在layout目录等等。
在XamarinAndroid应用程序中有两种方式访问这些资源:使用代码或声明式XML。
这些资源叫做默认资源可用于所有设备,除非指定了设备匹配的资源。另外,所有类型的资源都可以为特定设备指定专用资源。例如,可为用户本地化、屏幕大小、宽屏竖屏等提供资源。每种情况下,Android应用程序都可以加载特定资源,而无需开发人员编写代码。
特定资源由一个短字符串指定,叫做限定词(qualifier),加在资源目录的后面。例如,资源resources/drawable-de指定的图像用于德国区域的用户设备,而resources/drawable-fr资源图像用于法国区域的用户设备。下图是替换资源的范例,同一个应用程序运行在不同区域的设备上:
In the image above, the application resourcesare organized according to their type into these subdirectories: images will goin the drawable directory; views go in the layout subdirectory, etc.
There are two ways to access theseresources in a Xamarin.Android application: programmatically incode anddeclaratively in XML using a special XML syntax
These resources are called Default Resources and are used by all devicesunless a more specific match is specified. Additionally, every type of resourcemay optionally have Alternate Resources thatAndroid may use to target specific devices. For example, resources may beprovided to target the user’s locale, the screen size, or if the device isrotated 90 degrees from portrait to landscape, etc. In each of these cases,Android will load the resources for use by the application without any extracoding effort by the developer.
Alternate resources are specified by addinga short string, called a qualifier, to theend of the directory holding a given type of resources.
Forexample, resources/drawable-de will specify the images for devices that are setto a German locale, while resources/drawable-fr would hold images for devicesset to a French locale. An example of providing alternate resources can be seenin the image below where the same application is being run with just the localeof the device changing:
本文将全面的讲解资源的使用,包括如下主题:
Android默认资源—在代码和声明中使用默认资源,将特定类型资源如图像添加到应用程序。
特定配置的设备—应用程序支持不同屏幕分辨率和密度。
本地化—使用资源使应用程序支持不同区域的用户。
Thisarticle will take a comprehensive look at using resources and cover the followingtopics:
Android Resource Basics - Using default resources programmatically anddeclaratively, adding resource types such as images to an application.
Device Specific Configurations - Supporting the different screen resolutions anddensities in an application.
Localization – Usingresources to support the different regions an application may be used.
Part 1 –Android基本资源
Part 2 –默认资源
Part 3 –可选资源
Part 4 –为特定屏幕创建资源
Part 5 –应用程序本地化和字符串资源
Part 6 –使用AndroidAssets工具
大多数Android应用程序都具有一系列资源;至少包含用户界面布局XML文件。当Xamarin.Android应用程序创建的时候,Xamarin.Android项目模板会创建默认资源:
Almost all Androidapplications will have some sort of resources in them; at a minimum they oftenhave the user interface layouts in the form of XML files. When aXamarin.Android application is first created, default resources are setup bythe Xamarin.Android project template:
Resources目录中默认创建了5个资源文件:
Icon.png—应用程序默认图标
Main.axml—应用程序默认UI布局文件。注意Android使用.xml文件的扩展名,Xamarin.Android使用.axml文件扩展名。
Strings.xml—帮助应用程序本地化的字符串表
Resource.designer.cs—有Xamarin.Android自动生成和维护的文件,其中包含每个资源的唯一ID。其目的与使用Java开发Android应用程序中的R.java一致。由Xamarin.Android工具自动创建并随时重新生成。
AboutResources.txt—这个文件不是必须的,可以删除。只是描述了资源目录的概述和所包含的文件。
The five files thatmake up the default resources were created in the Resources folder:
Icon.png - The default icon for theapplication
Main.axml - The default user interfacelayout file for an application. Note that while Android uses the .xml file extension,Xamarin.Android uses the .axml file extension.
Strings.xml – A string table to helpwith localization of the application
Resource.designer.cs – This file is automatically generated and maintained byXamarin.Android and holds the unique ID’s assigned to each resource. This isvery similar and identical in purpose to the R.java file that an Androidapplication written in Java would have. It is automatically created by theXamarin.Android tools and will be regenerated from time to time.
AboutResources.txt – This is not necessary and may safely be deleted. It justprovides a high level overview of the Resources folder and the files in it.
创建资源和向特定资源类型目录中添加文件一样简单。下图中在项目中添加了一个德国区域的字符串资源。加入Strings.xml文件后,Xamarin.Android工具自动设置资源的Build Action属性:
Creating resources is as simple as adding files to the directoryfor the resource type in question. The screen shot below shows string resourcesfor German locales were added to a project. When Strings.xml was added to the file, the Build Action was automatically set toAndroid Resource by the Xamarin.Android tools:
这样Xamarin.Andriod工具就可以正确的将资源编译和嵌入到APK中了。如果没有为资源设置Build Action属性,文件将不会包含到APK中,加载资源会发生运行时错误,导致应用程序瘫痪。
同时,虽然Android只支持小写文件名的资源项,但Xamarin.Android不受此限制;可以使用大写和小写文件名。
资源加入到项目后,有两种方式使用资源—代码访问或XML中访问。
This allows theXamarin.Android tools to properly compile and embed the resources in to the APKfile. If for some reason the Build Action is not set to Android Resource, thenthe files will be excluded from the APK, and any attempt to load or access theresources will result in a run-time error and the application will crash.
Also, it’s importantto note that while Android only supports lowercase filenames for resourceitems, Xamarin.Android is a bit more forgiving; it will support both uppercaseand lowercase filenames.
Once resources havebeen added to a project, there are two ways to use them in an application –programmatically (inside code) or from XML files.
要在代码中访问资源文件,需要具有唯一标识ID。资源ID是Resource类定义的整形的成员,见Resource.designer.cs文件,如下所示:。
To access these files programmatically, they are assigned aunique resource ID. This resource ID is an integer defined in a special classcalled Resource, which is found in the file Resource.designer.cs,and looks something like this:
1 |
publicpartialclassResourcec {
publicpartialclassAttribute {
}
publicpartialclassDrawable { publicconstintIcon=0x7f020000; }
publicpartialclassId {
publicconstintTextview=0x7f050000; }
publicpartialclassLayout {
publicconstintMain=0x7f030000; }
publicpartialclassString {
publicconstintApp_Name=0x7f040001; publicconstintHello=0x7f040000; }
}
|
每个资源ID都包含在与资源类型匹配的嵌套类中。例如,项目中加入一个icon.png文件,Xamarin.Android自动更新Resource类,生成一个嵌套的Drawable类,包含叫做Icon的静态成员。这样就可以在代码中通过Resource.Drawable.Icon访问Icon.png文件。Resource类不能手动修改,否则将会被Xamarin.Android覆盖。
要在代码中引用资源,可使用Resources类按层次指定,语法如下:
@[<PackageName>.]Resource.<ResourceType>.<ResourceName>
PackageName – 提供资源的包,仅当资源在其他包中定义时才有用。
ResourceType – 就是上面提到的与资源类型对应的嵌套类
Resource Name – 资源的文件名称(不含扩展名)或定义在XML元素中的资源的android:name属性。
Each resource ID is contained inside a nested class thatcorresponds to the resource type. For example, when the fileicon.png was added to the project,Xamarin.Android updated the Resource class, creating a nested class calledDrawable with a constant inside named Icon. This allows the file Icon.png to bereferred to in code as Resource.Drawable.Icon. The Resource class should not bemanually edited, as any changes that are made to it will be overwritten by Xamarin.Android.
When referencingresources programmatically (in code), they can be accessed via the Resourcesclass hierarchy which uses the following syntax:
1 |
@[<PackageName>.]Resource.<ResourceType>.<ResourceName> |
PackageName - the package which is providingthe resource and is only required when resources from other packages are beingused.
ResourceType – This is the nested resourcetype that is within the Resource class described above.
Resource Name – this is the filename of theresource (without the extension) or the value of the android:name attribute forresources that are in an XML element.
XML中按如下语法引用资源:@[
PackageName – 提供资源的包,仅用于引用其他包中定义的资源。
ResourceType – Resource类中的嵌套资源类型。
Resource Name – 资源文件名(无扩展名),或定义在XML中的资源的android:name属性值。
例如在布局文件Main.axml中:
xml version="1.0" encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageViewandroid:id="@+id/myImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/flag"/>
LinearLayout>
本例中ImageView引用了叫做flag的drawable资源。ImageView将其src属性设置为@drawable/flag。当Activity启动后,Android将在Resource/Drawable目录中查找名为Activity1Image的文件并加载文件显示在ImageView中。当应用程序运行时可看到如下界面:
Resources in an XMLfile are accessed by a following a special syntax:@[
PackageName - the package which isproviding the resource and is only required when resources from other packagesare being used.
ResourceType – This is the nested resourcetype that is within the Resource class.
Resource Name – this is the filename of theresource (without the extension) or the value of the android:name attribute forresources that are in an XML element.
For example thecontents of a layout file, Main.axml, are as follows:
1 |
xml version="1.0" encoding="utf-8"?> <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ImageViewandroid:id="@+id/myImage" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/flag"/> LinearLayout> |
默认资源不是为特定设备和情况准备的,因此在没有指定特定资源情况下, Android系统会默认选择这些资源。因此这是最长创建的资源类型。他们按下图所示按照相应资源类型放在Resources目录的子目录中:
Defaultresources are items that are not specific to any particular device or formfactor, and therefore are the default choice by the Android OS if no morespecific resources can be found. As such, they’re the most common type ofresource to create. They’re organized into sub-directories of the Resourcesdirectory according to their resource type:
上图中,项目具有默认的drawable资源、布局、菜单、values(包含在xml中的简单值)。
下表列出完整的资源类型:
目录 |
描述 |
animator |
描述属性动画的XML文件。属性动画在API11(Android3.0)中引入,对对象属性提供动画。属性动画提供非常灵活强大的方式处理任意类型对象上的动画。 |
anim |
描述插值动画的XML文件。插值动画是一系列执行控件对象变换的动画指令,例如,图像旋转或变大字体。插值动画仅用于控件对象。 |
color |
定义了一系列颜色状态列表的XML。要理解颜色状态列表,假设有一个UI控件,如Button,可能具有不同状态如按下、不可用等,按钮可根据状态变化改变颜色。这个列表就表示为状态列表。 |
drawable |
Drawable资源是针对图像的常用概念,被编译到应用程序中,并可通过API访问或XML中引用。 例如位图文件(png、gif、jpg),以及可改变大小的位图Nine-Patches,状态列表,定义在XML中的通用图像等等。 |
layout |
定义在XML中的UI布局,如Activity或行列表。 |
menu |
定义在XML中的应用程序菜单,如选项菜单(Options Menus)、上下文菜单(Context Menus)、子菜单(submenus)。例如 Popup Menu Demo 或 Standard Controls范例。 |
raw |
任意二进制文件。以二进制文件显示编译到Android应用程序中。 |
values |
定义在XML中的简单的值。values目录中的XML文件可定义多种资源。例如一个XML定义字符串资源,另一个XML定义一系列颜色值。 |
xml |
同.NET配置文件一样的XML文件。应用程序可在运行时读取的任意XML文件。 |
In theimage above, the project has default values for drawable resources, layouts,menus, and values (XML files that contain simple values).
Acomplete list of resource types is in the table below:
Directory |
Description |
animator |
XML files that describe property animations. Property animations were introduced in API level 11 (Android 3.0) and provides for the animation of properties on an object. Property animations are a more flexible and powerful way to describe animations on any type of object. |
anim |
XML files that describe tween animations. Tween animations are a series of animation instructions to perform transformations on the contents of a View object, or example, rotation an image or growing the size of text. Tween animations are limited to only View objects. |
color |
XML files that describe a state list of colors. To understand color state lists, consider a UI widget such as a Button. It may make have different states such as pressed or disabled, and the button may change color with each change in state. The list is expressed in a state list. |
drawable |
Drawable resources are a general concept for graphics that can be compiled into the application and then accessed by API calls or referenced by other XML resources. Some examples of drawables are bitmap files (.png, .gif, .jpg), special resizable bitmaps known asNine-Patches, state lists, generic shapes defined in XML, etc. |
layout |
XML files that describe a user interface layout, such as an activity or a row in a list. |
menu |
XML files that describe application menus such as Options Menus, Context Menus, and submenus. For an example of menus checkout the Popup Menu Demo or the Standard Controls sample. |
raw |
Arbitrary files that are saved in their raw, binary form. These files are compiled into an Android application in a binary format. |
values |
XML files that contain simple values. An XML file in the values directory does not define a single resource, but instead can define multiple resources. For example one XML file may hold a list of string values, while another XML file may hold a list of color values. |
xml |
XML files that are similar in function to the .NET configuration files. These are arbitrary XML that can be read at run time by the application |
可选资源是为特定设备或运行时配置如语言、特定屏幕尺寸、像素密度定义的资源。如果Android发现有资源比默认资源更与设备类型、配置相匹配,则使用这个资源。如果没有找到与当前配置匹配的资源,则使用默认资源。下面将讨论Android应用程序如何决定使用哪个资源,在本地化资源小节中可选资源与默认资源一样,放在与资源类型对应的Resources目录的子目录中,命名为<资源类型>-<修饰符>
修饰符与特定设备配置相对应。名字中可以有多个修饰符,用点号间隔。例如,下图中的项目中为本地化、屏幕密度、买票大小、方向指定了可选资源:
Alternateresources are those resources that target a specific device or run-timeconfiguration such as the current language, particular screen size, or pixeldensity. If Android can match a resource that is more specific for a particulardevice or configuration than the default resource, then that resource will beused instead. If it does not find an alternate resource that matches thecurrent configuration, then the default resources will be loaded. How Androiddecides what resources will be used by an application will be covered in moredetail below, in the section Resource Location
Alternateresources are organized as a sub-directory inside the Resources folderaccording to the resource type, just like default resources. The name of thealternate resource subdirectory is in the form
Qualifieris a name that identifies a specific device configuration. There may be morethan one qualifier in a name, each of them separated by a dash. For example,the screenshot below shows a simple project that has alternate resources forvarious configurations such as locale, screen density, screen side, andorientation:
下面是向资源类型添加修饰符的规则:
1. 可有多个修饰符,用点号分割。
2. 修饰符只能出现一次。
3. 修饰符必须按下表的属性指定。
下表是可能使用的修饰符以及其参考说明。
修饰符 |
描述 |
MCC 和 MNC |
移动国家代码MCC(mobile country code)和移动网络代码MNC( mobile network code)。SIM卡可以指定MCC,而设备连接的网络指定MNC。虽然可根据特定区域确定移动国家代码,但推荐使用下面提供的语言修饰符。 例如,针对德国的资源,修饰符为mcc262.而US的T-Mobile,修饰符为mcc311-mnc026. 移动国家代码和移动网络代码请参考 http://mcclist.com/。 |
语言 |
两字母语言代码ISO 639-1 language code或两字母区域代码ISO-3166-alpha-2 region code。如果同时提供这两个修饰符,则使用-r间隔。 例如,针对法语本地化资源使用fr作为修饰符。加拿大法语区域使用fr-rCa。 语言代码和区域代码更多信息见Codes for the Representation of Names Of Languages 和 Country names and code elements |
最小宽度 |
指定执行应用程序的设备的最小设备宽度。详细信息见下面的范例(为各种屏幕创建资源)。可用于ADP13(Android3.2)或更高版本。 例如,修饰符sw320dp用于高度和宽度都大于等于320dp的设备。 |
有效宽度 |
用w 可用于API13(Android3.2)以及更高版本。 例如:w720dp指定宽度至少为720dp的设备。 |
有效高度 |
以h 例如,h720dp表示高度至少是720dp的设备。 |
屏幕尺寸 |
这个修饰符指定资源使用的设备屏幕尺寸。更多信息见下面的范例(为各种屏幕创建资源)。 可指定值为small、normal、large、xlarge。 可用于API9(Android2.3、Android2.3.1、Android2.3.2) |
屏幕视角(Screen aspect) |
基于屏幕视角,而不是屏幕方向。Long表示宽屏。 在API4(Android1.6引入)。 可选值long、notlong。 This is based on the aspect ratio, not the screen orientation. A long screen is wider. Added in API level 4 (Android 1.6). Possible values are long and notlong. |
屏幕方向 |
竖屏或宽屏。可在应用程序运行时改变。 可选值port、land。 Portrait or landscape screen orientation. This can change during the lifetime of an application. Possible values are port and land. |
停靠模式 |
For devices in a car dock or a desk dock. Added in API level 8 (Android 2.2.x). Possible values are car and desk. |
夜晚模式 |
应用程序是否运行在夜间。应用程序运行时会改变,为开发者提供一个机制给用户提供夜间使用的UI。 API8(Android2.2.X)引入。 可能值night和notnight. |
屏幕像素密度Screen pixel density (dpi) |
物理屏幕单位面积中像素数。典型表示为每英寸多少点(dpi)。 可选值: ldpi—低密度屏幕 mdpi-中等密度屏幕 hdpi-高密度屏幕 xhdpi-超高密度屏幕 nodpi-资源不能被缩放 tvdpi-介于mdpi与hdpi之间。API13(Android3.2)引入。 |
触摸屏类型Touchscreen type |
设备触摸屏类型。可能只notouch(无触摸屏)、stylus(触摸屏电阻元件适合触摸笔)、finger(手指触摸屏) |
键盘可用性Keyboard availability |
制定可用键盘类型。可能在应用程序运行中改变—例如用户连接硬件键盘。可能值: keysexposed–设备具有键盘。如果无软键盘,则只能开启硬件键盘。 keyshidden–设备具有硬件键盘但已隐藏,而且未启动软键盘。 keyssoft–设备启动了软键盘。 |
主要文字输入方式Primary text input method |
指定可用的硬件键盘。可能值: nokeys–无硬件键盘 qwerty –标准键盘 12key -12键硬件键盘 |
导航键可用性Navigation key availability |
5-way或方向键有效。运行时可能改变。可能值: navexposed–导航键可用 navhidden–导航键不可用 |
主要非触摸导航方法 Primary non-touch navigation method |
设备可用导航方式。可能值: nonav–只能使用触摸屏导航 dpad–可用方向键导航 trackball –可用轨迹球导航 wheel –一或多个滚轮导航 |
平台版本(API版本)Platform version (API level) |
设备支持的API版本,v 例如,V11指API11(Android3.0)设备。 |
Thefollowing rules apply when adding qualifiers to a resource type:
1. Theremay be more than one qualifier, with each qualifier separated by a dash.
2. The qualifiers maybe specified only once.
3. Qualifiers must be in the order they appear in the table below.
The table below lists the possible qualifiers that may be used and is providedfor reference.
Qualifier |
Description |
MCC and MNC |
The mobile country code (MCC) and optionally the mobile network code (MNC). The SIM card will provide the MCC, while the network the device is connected to will provide the MNC. Although it is possible to target locales using the mobile country code, the recommend approach is to use the Language qualifier specified below. For example, to target resources to Germany, the qualifier would be mcc262. To target resources for T-Mobile in the U.S., the qualifier is mcc310-mnc026. For a complete list of mobile country codes and mobile network codes see http://mcclist.com/. |
Language |
The two-letter ISO 639-1 language code and optionally followed by the two-letter ISO-3166-alpha-2 region code. If both qualifiers are provided, then they are separated by an –r. For example, to target French-speaking locales then the qualifier of fr is used. To target French-Canadian locales, the fr-rCA would be used. For a complete list of language codes and region codes, see Codes for the Representation of Names Of Languages and Country names and code elements. |
Smallest Width |
Specifies the smallest screen width the application is meant to execute on. Covered in more detail in the section Creating Resources for Varying Screens below. Available in in API level 13 (Android 3.2) and above. For example, the qualifier sw320dp is used to target devices whose height and width is at least 320dp. |
Available Width |
The minimum width of the screen in the format w Available in in API level 13 (Android 3.2) and above. Example: the qualifier w720dp is used to target devices that have a width of least 720dp. |
Available Height |
The minimum height of the screen in the format h Available in in API level 13 (Android 3.2) and above. For example, the qualifier h720dp is used to target devices that have a height of least 720dp |
Screen size |
This qualifier is a generalization of the screen size that these resources are for. It is covered in more detail in the section Creating Resources for Varying Screens below. Possible values are small, normal, large, and xlarge. Added in API level 9 (Android 2.3/Android 2.3.1/Android 2.3.2) |
Screen aspect |
This is based on the aspect ratio, not the screen orientation. A long screen is wider. Added in API level 4 (Android 1.6). Possible values are long and notlong. |
Screen Orientation |
Portrait or landscape screen orientation. This can change during the lifetime of an application. Possible values are port and land. |
Dock mode |
For devices in a car dock or a desk dock. Added in API level 8 (Android 2.2.x). Possible values are car and desk. |
Night mode |
Whether or not the application is running at night or in the day. This may change during the lifetime of an application and is meant to give developers an opportunity to use darker versions of an interface at night. Added in API level 8 (Android 2.2.x). Possible values are night and notnight. |
Screen pixel density (dpi) |
The number of pixels in a given area on the physical screen. Typically expressed as dots per inch (dpi). Possible values are: ldpi - Low density screens. |
Touchscreen type |
Specifies the type of touchscreen a device may have. Possible values are notouch (no touch screen), stylus (a resistive touchscreen suitable for a stylus), and finger (a touchscreen). |
Keyboard availability |
Specifies what kind of keyboard is available. This may change during the lifetime of an application – for example when a user opens a hardware keyboard. Possible values are: keysexposed - The device has a keyboard available. If there is no software keyboard enabled, then this is only used when the hardware keyboard is opened. |
Primary text input method |
Use to specify what kinds of hardware keys are available for input. Possible values are: nokeys - There are no hardware keys for input. |
Navigation key availability |
For when 5-way or d-pad (directional-pad) navigation is available. This can change during the lifetime of your application. Possible values are: navexposed - the navigational keys are available to the user |
Primary non-touch navigation method |
The kind of navigation available on the device. Possible values are: nonav - the only navigation facility available is the touch screen |
Platform version (API level) |
The API level supported by the device in the format v For example, v11 will target an API level 11 (Android 3.0) device. |
For more complete information aboutresource qualifiers see Providing Resources onthe Android Developers website.
Android应用程序非常可能包含多个资源。理解Android如何为运行在设备上的应用程序选择资源是很重要的。
Android选择资源基于如下规则:
排除相反的修饰符—例如,如果设备是竖屏的,所有宽屏资源目录被排除。
忽略不支持的修饰符—并非所有的API版本都支持这些修饰符。如果resources目录中包含设备不支持的修饰符,将这个资源目录排除。
确定更高级别的修饰符—根据上面表顺序(从上到下),选择更高级别的修饰符。
具有多个符合要求的修饰符目录—如果有多个资源目录匹配,则选择最高优先级修饰符(上表从上到下顺序)
这些规划可用下图描述:
It isvery possible and likely that an Android application will contain manyresources. It is important to understand how Android will select the resourcesfor an application when it runs on a device.
Android determinesthe resources base by iterating over the following test of rules:
Eliminate contradictory qualifiers – for example, if the device orientation isportrait, then all landscape resource directories will be rejected.
Ignore qualifiers not supported - Not all qualifiers are available to all API levels.If a resource directory contains a qualifier that is not supported by thedevice, then that resource directory will be ignored.
Identify the next highest priority qualifier – referring to the table above select the nexthighest priority qualifier (from top to bottom).
Keep any resource directories for qualifier – if there are any resource directories that matchthe qualifier to the table above select the next highest priority qualifier(from top to bottom).
Theserules are also illustrated in the following flowchart:
如果系统查找特定密度相关的资源,但没有找到,将尝试定位其他密度资源并缩放。Android可能不必使用默认资源。例如,要查找低密度资源但不存在,Android可能越过默认资源和中等密度资源选择高密度版本资源。这样做是因为高密度资源可以缩放0.5倍,比缩放中等密度资源缩放0.75倍带来的视觉问题更少。
假如应用程序具有如下drawable资源目录:
When thesystem is looking for density-specific resources and cannot find them, it willattempt to locate other density specific resources and scale them. Android maynot necessarily use the default resources. For example, when looking for alow-density resource and it is not available, Android may select high-densityversion of the resource over the default or medium-density resources. It doesthis because the high-density resource can be scaled down by a factor of 0.5,which will result in fewer visibility issues than scaling down a medium-densityresource which would require a factor of 0.75.
As anexample, consider an application that has the following drawable resourcedirectories:
1 |
drawable drawable-en drawable-fr-rCA drawable-en-port drawable-en-notouch-12key drawable-en-port-ldpi drawable-port-ldpi drawable-port-notouch-12key |
应用程序运行在如下配置的设备上:
And nowthe application is run on a device with the following configuration:
· Locale –en-GB
· Orientation –port
· Screen density –hdpi
· Touchscreen type – notouch
· Primary input method – 12key
由于制定了en-GB区域将法语资源忽略:
To begin with, the French resources areeliminated as they conflict with the locale of en-GB:
1 |
drawable drawable-en drawable-fr-rCA drawable-en-port drawable-en-notouch-12key drawable-en-port-ldpi drawable-port-ldpi drawable-port-notouch-12key |
接着根据上表顺序选择第一个修饰符:MCC和MNC。没有制定这个修饰符的资源目录,忽略MCC/MNC代码。
下一个修饰符是语言。有资源与语言匹配。忽略所有不与语言代码en不匹配的资源目录:
Next,the first qualifier is selected from the qualifiers table above: MCC and MNC.There are no resource directories that contain this qualifier so the MCC/MNCcode is ignored.
The next qualifier is selected, which isLanguage. There are resources that match the language code. All resourcedirectories that do not match the language code of en arerejected:
1 |
drawable drawable-en drawable-fr-rCA drawable-en-port drawable-en-notouch-12key drawable-en-port-ldpi drawable-port-ldpi drawable-port-notouch-12key |
接下来是屏幕方向,忽略所有不与屏幕方向不匹配的资源目录:
The next qualifier that is present is for screenorientation, so all resource directories that do not match the screenorientation of port are eliminated:
1 |
drawable drawable-en drawable-fr-rCA drawable-en-port drawable-en-notouch-12key drawable-en-port-ldpi drawable-port-ldpi drawable-port-notouch-12key |
接着是屏幕密度,ldpi,最后排除多余的资源目录:
Next is the qualifier for screendensity, ldpi, which results in the exclusion of one more resourcedirectory:
1 |
drawable drawable-en drawable-fr-rCA drawable-en-port drawable-en-notouch-12key drawable-en-port-ldpi drawable-port-ldpi drawable-port-notouch-12key |
上面分析过程的结果是,Android为设备选择drawable-en-port-ldpi目录下的drawable资源。
注意:屏幕尺寸修饰符选择比较特例。可能会选择为小屏幕设计的资源,而不使用为当前设备提供的资源。例如,大屏幕设备可能使用正常尺寸屏幕的资源。但反向不成立,大屏幕设备不会使用超大屏幕的资源。如果Android不能找到与屏幕尺寸匹配的资源,应用程序会崩溃。
As a result of this process, Android willuse the drawable resources in the resource directory drawable-en-port-ldpi for the device.
NOTE: Thescreen size qualifiers provide one exception to this selection process. It is possiblefor Android to select resources that are designed for a smaller screen thanwhat the current device provides. For example, a large screen device may usethe resources provide for a normal sized screen. However the reverse of this isnot true: the same large screen device will not use the resources provided foran xlarge screen. If Android cannot find a resource set that matches a givenscreen size, the application will crash.
Android会运行在这种设备上,需要适应各种分辨率、屏幕大小、屏幕密度。Android会通过缩放使应用程序可运行在这些设备上,但用户体验不是很好。例如,图像可能很模糊,图像相对于屏幕区域太大或太小导致布局重叠或距离太远。
Android itselfruns on many different devices, each having a wide variety of resolutions,screen sizes, and screen densities. Android will perform scaling and resizingto make your application work on these devices, but this may result in asub-optimal user experience. For example, images may appear blurry, images mayoccupy to much (or not enough) screen space which causes the position of UIelements in the layout will overlap or be too far apart.
要支持多屏幕开发必须先了解几个词汇和概念。
屏幕大小—应用程序可显示的物理区域
屏幕密度—特定屏幕区域像素数。常用单位是每英寸点数(dpi)。
分辨率—屏幕总像素数。程序开发中分辨率不如屏幕大小和密度重要。
密度无关的像素(dp)—虚拟的度量单位,用来设计密度无关的布局。用如下公式将dp转换为屏幕像素数:px=dp*dpi/160
方向—为了处理宽屏(宽度大于高度)引入屏幕方向概念。相反竖屏高度大于宽度。方向可在运行时旋转设备来改变。
注意前三个概念是相关关联的—增加分辨率但不增加密度将增加屏幕尺寸。然而同时增加密度和分辨率,屏幕尺寸不变。
为了处理这种复杂性,Android框架为布局引入了密度无关的像素(dp)概念。使用密度无关像素,UI元素在不同密度设备上以同样物理大小显示。
A few termsand concepts are important to understand in order to support multiple screens.
Screen Size – The amount of physical space for displaying yourapplication
Screen Density – The number of pixels in any given area on the screen.The typical unit of measure is dots per inch (dpi).
Resolution – The total number of pixels on the screen. Whendeveloping applications, resolution is not as important as screen size anddensity.
Density-independent pixel (dp) – This is a virtual unit of measure to allow layoutsto be designed independent of density. To convert dp into screen pixels thefollowing formula is used: px=dp*dpi/160
Orientation –The screen’s orientation is considered to be landscape when itis wider than it is tall. In contrast, portrait orientation is when the screenis taller than it is wide. The orientation can change during the lifetime of anapplication as the user rotates the device.
Notice thatthe first three of these concepts are inter-related – increasing the resolutionwithout increasing the density will increase the screen size. However if boththe density and resolution are increased then the screen size can remain unchanged.This relationship between screen size, density and resolution complicate screensupport very quickly.
To help deal with this complexity, the Androidframework prefers to use density-independentpixels (dp) forscreen layouts. By using density independent pixels, UI elements will appear tothe user to have the same physical size on screens with different densities.
Android为在各种配置的屏幕上绘制布局做了大量工作。然而,可以做一些事情提升系统的表现。
在布局中使用密度无关像素来替代实际像素,可确保布局是密度无关的。Android会在运行时缩放drawable到适当大小。然而,缩放可能会导致位图模糊。要避免这种情况就需要为不同密度提供可选资源。当设计适应多种分辨率和屏幕密度的程序时,可准备好高分辨率或密度的图像,然后缩小尺寸。这样可以避免改变大小时模糊或失真。
Androidhandles most of the work to render the layouts properly for each screenconfiguration. However, there are some actions that can be taken to help thesystem out.
The use ofdensity-independent pixels instead of actual pixels in layouts is sufficient inmost cases to ensure density independence. Android will scale the drawables atruntime to the appropriate size. However, it is possible that this scaling willcause bitmaps to appear blurry. To avoid this, it may be necessary to supplyalternate resources for the different densities. When designing devices formultiple resolutions and screen densities it will prove easier to start withthe higher resolution or density images and then scale down. This will preventany blurring or distortion that may result from the resizing.
声明屏幕大小确保只有支持的设备才能下载应用程序。可在AndroidManifest.xml文件中的
要在Xamarin Android中进行配置,首先将AndroidManifest.xml文件添加到项目:
Declaring the screen size ensures that only supporteddevices can download the application. This is accomplished by setting the
To do this inXamarin.Android, it is necessary to first add an AndroidManifest.xml file to the project:
将会在Properties目录中添加AndroidManifest.xml文件。然后文件包含一个
虽然Android可以根据屏幕尺寸缩放,但有的情况下效果却不够理想。可能需要为大屏幕增加UI元素大小,或需要为小屏幕移动UI元素。
自从API13(Android3.2)开始弃用sw
例如如果布局需要最小700dp宽的屏幕,可选布局应该放在layout-sw700dp目录中:
AlthoughAndroid will resize according the screen size, this may not be sufficient insome cases. It may be desirable to increase the size of some UI elements on alarger screen, or to change the positioning of the UI elements for a smallerscreen.
Starting withAPI Level 13 (Android 3.2), the screen sizes are deprecated in favor of usingthe sw
For example,if a layout required a minimum 700dp of screen width, the alternate layoutwould go in a folderlayout-sw700dp:
作为参考,这里列出各种设备:
Typical phone – 320dp: 传统电话
A 5” tablet / “tweener” device – 480dp: 如三星Note
A 7” tablet – 600dp: 如Barnes & Noble Nook
A 10” tablet – 720dp: 如MotorolaXoom
对于API12(Android3.1)的应用程序,为各种屏幕尺寸定义的布局文件应该存放在用small、normal、large、xlarge修饰符指定目录中。例如下图所示,定义了四种不同屏幕尺寸可选资源:
As aguideline, here are some numbers for various devices:
Typical phone – 320dp: a typical phone
A 5” tablet / “tweener” device – 480dp: such as the Samsung Note
A 7” tablet – 600dp: such as the Barnes & Noble Nook
A 10” tablet – 720dp: such as the Motorola Xoom
Forapplications that target API levels up to 12 (Android 3.1), the layouts shouldgo in directories that use the qualifiers small/normal/large/xlarge as generalizationsof the various screen sizes that are available in most devices. For example, inthe image below, there are alternate resources for the four different screensizes:
下面比较API13之前密度无关像素的屏幕尺寸修饰符:
426dp x 320dp -- small
470dp x 320dp -- normal
640dp x 480dp -- large
960dp x 720dp -- xlarge
API13和更高版本中新定义的修饰符比老版本API中的修饰符具有更高的优先级,有的时候有必要同时用这两种修饰符创建可选资源,如下所示:
The followingis a comparison of how the older pre-API Level 13 screen size qualifierscompare to density-independent pixels:
426dp x 320dp is small
470dp x 320dpis normal
640dp x 480dpis large
960dp x 720dpis xlarge
The newerscreen size qualifiers in API level 13 and up have a higher precedence than theolder screen qualifiers of API levels 12 and lower. For applications that willspan the old and the new API levels, it may be necessary to create alternateresources using both sets of qualifiers as shown in the following screen shot:
尽管Android需要为设备缩放位图,但位图可能不能完美的缩放:会变得失真和模糊。为屏幕密度提供适合的位图可以解决这个问题。
例如,下图中不提供特定屏幕密度的资源,可能会导致布局和显示问题。
AlthoughAndroid will scale bitmaps as necessary for a device, the bitmaps themselvesmay not elegantly scale up or down: they may become fuzzy or blurry. Providingbitmaps appropriate for the screen density will mitigate this problem.
For example,the image below is an example of layout and appearance problems that may occurwhen density specify resources are not provided.
下面的截图是为特定屏幕密度指定资源:
Compare thisto a layout that is designed with density specific resources:
为各种屏幕分辨率窗体位图是比较枯燥的。为此Google提供了一个在线工具为创建这些位图减少工作量,这个工具叫做 Android Asset Studio。
The creation of these bitmaps of various densities canbe a bit tedious. As such, Google has created an online utility which canreduce some of the tedium involved with the creation of these bitmaps call the Android Asset Studio.
这个站点可以只需提供一个位图就可以创建四种屏幕密度图像。Android Asset Studio可以创建自定义图像,并可以让开发者下载压缩文件:
This websitewill help with creation of bitmaps that target the four common screen densitiesby providing one image. Android Asset Studio will then create the bitmaps withsome customizations and then allow them to be downloaded as a zip file:
Andriod运行在大量设备上,而且屏幕尺寸和屏幕密度的组合也是具有很多种情况。这个窍门可以让我们话费最小努力实现多设备支持:
只针对必要的情况进行开发设计—有大量不同的设备,但进行特别设计开发的设备类型表现最佳。 Screen Size and Density是Google提供的屏幕尺寸、屏幕密度分别矩阵,给出对这种屏幕所付出努力的比例。
使用dp替代像素—在屏幕密度变化时使用像素会导致麻烦出现。不要硬编码像素值,而是使用dp。
尽可能避免绝对布局(AbsoluteLayout ) – 在API3(Android1.5)及过时了,容易导致脆弱的布局。不应该在使用。而应该使用更灵活的布局如LinearLayout, RelativeLayout, GridLayout.
选择一个默认的布局方法 – 例如不要同时定义layout-landand和layout-port可选资源,将宽布局资源放在layout中,而竖屏资源放在layout-port中
使用高度和宽带布局参数 – 当在XML布局文件中定义UI元素,Android应用程序使用wrap_content和fill_parent比使用像素或密度无关单位能更好的适应不同设备。这些密度值导致Android缩放图像。基于这些原因,密度无关单元更适用在定义UI元素内边框或外边框。
Android runson a bewildering number of devices, and the combination of screen sizes andscreen densities can seem overwhelming. The following tips can help minimizethe effort necessary to support various devices:
Only Design and Develop for What you Need – There are a lot of different devices out there, butsome exist in rare form factors that may take a lot of effort to design anddevelop for. The Screen Size and Density dashboard is a page provided by Google that providesdata on breakdown of the screen size/screen density matrix. This breakdownprovides insight on how to development effort on supporting screens.
Use DPs rather than Pixels - Pixels become troublesome as screen densitychanges. Do not hardcode pixel values. Avoid pixels in favor of dp(density-independent pixels).
Avoid AbsoluteLayout Wherever Possible – it is deprecated in API level 3 (Android 1.5) andwill result in brittle layouts. It should not be used. Instead, try to use moreflexible layout widgets such as LinearLayout, RelativeLayout, or the new GridLayout.
Pick one layout orientation as your default – For example, instead of providing the alternateresources layout-landand layout-port, putthe resources for landscape in layout, and the resources for portrait into layout-port.
Use LayoutParams for Height and Width - When defining UI elements in an XML layout file, anAndroid application using the wrap_content and fill_parent values will have more success ensure aproper look across different devices than using pixel or density independentunits. These dimension values cause Android to scale bitmap resources asappropriate. For this same reason, density-independent units are best reservedfor when specifying the margins and padding of UI elements.
Android应用程序应该在所有支持配置的设备上进行测试。考虑到在所有真实设备上测试时不可能的,这时可使用模拟器和每种设备配置安装的Android虚拟设备进行测试。
Android SDK提供了一些模拟器皮肤可用于创建不同尺寸、密度、分辨率设备的AVD。很多设备厂商都提供了皮肤。
也可选择三方提供的测试服务。这些服务打包成APK,运行在不同设备中,将应用程序运行情况反馈回来。
An Android applicationneeds to be tested against all configurations that will be supported. Ideallydevices should be tested on the actual devices themselves but in many casesthis is not possible or practical. In this case the use of the emulator andAndroid Virtual Devices setup for each device configuration will be useful.
The AndroidSDK provides some emulator skins may be used to create AVD’s will replicate thesize, density, and resolution of many devices. Many of the hardware vendorslikewise provide skins for their devices.
Another optionis to use the services of a third party testing service. These services willtake an APK, run it on many different devices, and then provide feedback howthe application worked.
Apkudo
TheBeta Family
Perfecto Mobile
第五部分-应用程序本地化和字符串资源
应用程序本地化是通过为目标区域提供可选资源来实现的。例如,可为各个国家提供本地化语言字符串、与文化相关的颜色和布局。无需编写代码Android就可以在运行时根据设备区域加载适当的资源。
例如下图是同一个应用程序运行在三个不同地区的截图,按钮上的文字会根据设备区域调整:
Applicationlocalization is the act of providing alternate resources to target a specificregion or locale. For example, you might provide localized language strings forvarious countries, or you might change colors or layout to match particularcultures. Android will load and use the resources appropriate for the device’slocale at runtime time without any changes to the source code.
Forexample, the image below shows the same application running in three differentdevice locales, but the text displayed in each button is specific to the localethat each device is set to:
本例中布局文件Main.axml如下:
In thisexample, the contents of a layout file, Main.axml looks somethinglike this:
1 |
xml version="1.0" encoding="utf-8"?> <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <Button android:id="@+id/myButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> LinearLayout> |
上例中按钮上的文字使用字符串资源ID进行加载。
In theexample above, the string for the button was loaded from the resources byproviding the resource ID for the string.
本地化比较耗时,因此很多应用程序不做本地化处理。为了降低本地化影响,遵守如下规则:
尽量少的布局文件。支持所有本地化的单个灵活性强的布局更好维护。
确保对默认布局进行测试。如因为某些因素(如丢失)导致默认资源无法加载,会导致应用程序崩溃。
仅创建必要的本地化资源。录入,虽然世界上有很多地区将法语,也没有必要对每个法语地区提供支持。支持这些区域会投入大量无必要的工作,不利于应用程序的开发和维护。
Localizationcan be a time consuming process. As such, most applications are not localized.In order to minimize the impact that localization issues can cause, followingthese tips:
Make asfew layouts as possible. A single, flexible layout supporting all locales willbe easier to maintain.
Makesure to test the default locale. Your application will crash if the defaultresources cannot be loaded for some reason (i.e. they are missing).
Onlycreate the localized resources you need. For example, although there are manyFrench speaking nations in the world, it may not be necessary to support eachindividual French region. Supporting these regions may create extra work andunnecessary effort in the application’s development and maintenance.
Assets为应用程序提供了任何必须的文件,如文本、xml、字体、音乐、视频。如果将这些文件包含到资源中,Android将按资源来处理这些文件,而不能当做二进制文件来处理。如果要使用原始的数据,可使用Assets。
加入到项目中的Asset的文件,应用程序可使用AssetManager来访问。
在这个简单的范例中,在项目中加入了文本文件,使用AssetManager来访问,并显示在TextView中。
Assetsprovide a way to include arbitrary files like text, xml, fonts, music, andvideo in your application. If you try to include these files as"resources", Android will process them into its resource system andyou will not be able to get the raw data. If you want to access data untouched,Assets are one way to do it.
Assets added to your project will show upjust like a file system that can read from by your application usingAssetManager.
In this simple demo, we are going to add atext file asset to our project, read it using AssetManager, and display it ina TextView.
Asset资源位于项目的Assets目录。向目录中添加新的文本文件read_asset.txt。加入一些文本如“I came from an asset!”。
接下来告诉VisualStudio这是一个asset文件。启动属性窗口设置文件的BuildAction属性为AndroidAsset。
Assets go in the Assets folderof your project. Add a new text file to this folder called read_asset.txt. Placesome text in it like "I came from an asset!".
Next you have to tell Visual Studio thatthis is an asset file. Bring up the properties window for the file and set theBuildAction to AndroidAsset:
现在当编译打包应用程序的时候文件将被添加进来。
Now thefile will be build into our application when it is compiled and packaged.
使用AssetManager读取Asset。Activity提供了一个AssetManager类型的Assets属性。下面代码中,打开read_asset.txt,读取其中内容,显示在TextView中。
Assets are read using an AssetManager. Activities provide an Assets property as a shortcut to an AssetManager. In thefollowing code, we open our "read_asset.txt" asset, read thecontents, and display it using a TextView.
1 |
protectedoverridevoidOnCreate (Bundle bundle) { base.OnCreate (bundle);
// Create a new TextView and set it as our view vartv=newTextView (this);
// Read the contents of our asset string content; using (StreamReadersr=newStreamReader (Assets.Open ("read_asset.txt"))) { content =sr.ReadToEnd (); }
// Set TextView.Text to our asset content tv.Text= content; SetContentView (tv); } |
运行应用程序如图所示:
本文讲述如何在Xamarin Android应用程序中使用Android资源。介绍了默认资源和可选资源,以及如何在本地化中使用它们。然后讲述对各种Android设备屏幕的支持,以及如何使用Android资源实行各种设备统一的UI界面。
Thisarticle covered using Android resources in a Xamarin.Android application. Itintroduced default and alternate resources, and how they may be used to supportlocalization. It then examined issues surrounding the screens of various Androiddevices and how Android resources may be used to provide a consistent UI acrossdevices.