700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > Xamarin Getting Started翻译系列五--Android资源

Xamarin Getting Started翻译系列五--Android资源

时间:2021-02-17 23:06:05

相关推荐

Xamarin Getting Started翻译系列五--Android资源

Android资源

本文介绍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.

概述Overview

很少有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 thedrawabledirectory; views go in thelayoutsubdirectory, etc.

There are two ways to access theseresources in a Xamarin.Android application:programmaticallyincode anddeclarativelyin XML using a special XML syntax

These resources are calledDefault Resourcesand are used by all devicesunless a more specific match is specified. Additionally, every type of resourcemay optionally haveAlternate ResourcesthatAndroid 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 aqualifier, 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基本资源

大多数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.xmlfile extension,Xamarin.Android uses the.axmlfile 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. WhenStrings.xmlwas added to the file, theBuild Actionwas 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 fileResource.designer.cs,and looks something like this:

每个资源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.pngwas 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:

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中引用资源

XML中按如下语法引用资源:@[<PackageName>:]<ResourceType>/<ResourceName>。

PackageName –提供资源的包,仅用于引用其他包中定义的资源。

ResourceType –Resource类中的嵌套资源类型。

Resource Name –资源文件名(无扩展名),或定义在XML中的资源的android:name属性值。

例如在布局文件Main.axml中:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayoutxmlns:android="/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>:]<ResourceType>/<ResourceName>.

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:

Thisexample has anImageViewthatrequires a drawable resource named flag. The ImageView has its src attributeset to @drawable/flag. When the activity starts, Android will look inside thedirectory Resource/Drawable for a file named Activity1Image and load that fileand display it in the ImageView. When this application is run, it would looksomething like the following image:

第二部分-默认资源

默认资源不是为特定设备和情况准备的,因此在没有指定特定资源情况下, 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中的简单值)。

下表列出完整的资源类型:

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:

第三部分-可选资源

可选资源是为特定设备或运行时配置如语言、特定屏幕尺寸、像素密度定义的资源。如果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<ResourceType>-<Qualifier>.

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.修饰符必须按下表的属性指定。

下表是可能使用的修饰符以及其参考说明。

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.

For more complete information aboutresource qualifiers seeProviding Resourcesonthe Android Developers website.

Android如果决定使用哪个资源

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:

应用程序运行在如下配置的设备上:

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 ofen-GB:

接着根据上表顺序选择第一个修饰符: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 ofenarerejected:

接下来是屏幕方向,忽略所有不与屏幕方向不匹配的资源目录:

The next qualifier that is present is for screenorientation, so all resource directories that do not match the screenorientation ofportare eliminated:

接着是屏幕密度,ldpi,最后排除多余的资源目录:

Next is the qualifier for screendensity,ldpi, which results in the exclusion of one more resourcedirectory:

上面分析过程的结果是,Android为设备选择drawable-en-port-ldpi目录下的drawable资源。

注意:屏幕尺寸修饰符选择比较特例。可能会选择为小屏幕设计的资源,而不使用为当前设备提供的资源。例如,大屏幕设备可能使用正常尺寸屏幕的资源。但反向不成立,大屏幕设备不会使用超大屏幕的资源。如果Android不能找到与屏幕尺寸匹配的资源,应用程序会崩溃。

As a result of this process, Android willuse the drawable resources in the resource directorydrawable-en-port-ldpifor 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 usedensity-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文件中的<supports-screens>元素中指定。这个元素用来指定应用程序支持的屏幕尺寸。如果应用程序的布局可以正确的填充屏幕则认为支持这种屏幕。使用清单元素,如果应用程序不适合指定的屏幕则不会出现在Google Play中。然而,应用程序还是可以运行在不支持屏幕的设备上,只是布局可能模糊和像素化。

要在Xamarin Android中进行配置,首先将AndroidManifest.xml文件添加到项目:

Declaring the screen size ensures that only supporteddevices can download the application. This is accomplished by setting the<supports-screens>element in theAndroidManifest.xmlfile.This element is used to specify what screen sizes are supported by theapplication. A given screen is considered to be supported if the applicationcan properly it’s layouts to fill screen. By using this manifest element, theapplication will not show up inGoogle Playfor devices that do not meet the screenspecifications. However, the application will still run on devices withunsupported screens, but the layouts may appear blurry and pixelated.

To do this inXamarin.Android, it is necessary to first add anAndroidManifest.xmlfile to the project:

将会在Properties目录中添加AndroidManifest.xml文件。然后文件包含一个<supports-screens>节点:

TheAndroidManifest.xmlwillbe added to the Properties directory. The file is then edited to include<supports-screens>:

为不同屏幕尺寸提供可选布局

虽然Android可以根据屏幕尺寸缩放,但有的情况下效果却不够理想。可能需要为大屏幕增加UI元素大小,或需要为小屏幕移动UI元素。

自从API13(Android3.2)开始弃用sw<N>dp屏幕尺寸修饰符。为各种布局需要的空间指定新的修饰符。强烈建议运行在Android3.2或更高版本的应用程序使用新的修饰符。

例如如果布局需要最小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 usingthesw<N>dpqualifier. This new qualifier declaresthe amount of space a given layout needs. It is strongly recommended thatapplications that are meant to run on Android 3.2 or higher should be usingthese newer qualifiers.

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 qualifierssmall/normal/large/xlargeas 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 issmall

470dp x 320dpisnormal

640dp x 480dpislarge

960dp x 720dpisxlarge

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 theAndroid 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. TheScreen Size and Densitydashboard 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).

AvoidAbsoluteLayoutWherever 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 asLinearLayout,RelativeLayout, or the newGridLayout.

Pick one layout orientation as your default– For example, instead of providing the alternateresourceslayout-landandlayout-port, putthe resources for landscape inlayout, and the resources for portrait intolayout-port.

Use LayoutParams for Height and Width- When defining UI elements in an XML layout file, anAndroid application using thewrap_contentandfill_parentvalues 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.axmllooks somethinglike this:

上例中按钮上的文字使用字符串资源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.

使用AndroidAssets资源

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

在项目中添加Asset

Asset资源位于项目的Assets目录。向目录中添加新的文本文件read_asset.txt。加入一些文本如“I came from an asset!”。

接下来告诉VisualStudio这是一个asset文件。启动属性窗口设置文件的BuildAction属性为AndroidAsset。

Assets go in theAssetsfolderof your project. Add a new text file to this folder calledread_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 theBuildActiontoAndroidAsset:

现在当编译打包应用程序的时候文件将被添加进来。

Now thefile will be build into our application when it is compiled and packaged.

读取Assets

使用AssetManager读取Asset。Activity提供了一个AssetManager类型的Assets属性。下面代码中,打开read_asset.txt,读取其中内容,显示在TextView中。

Assets are read using anAssetManager. Activities provide anAssetsproperty as a shortcut to an AssetManager. In thefollowing code, we open our "read_asset.txt" asset, read thecontents, and display it using aTextView.

运行应用程序

运行应用程序如图所示:

结论

本文讲述如何在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.

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。