【翻译】(13)XML布局
【翻译】(13)XML布局
?
see
http://developer.android.com/guide/topics/ui/declaring-layout.html
?
原文见
http://developer.android.com/guide/topics/ui/declaring-layout.html
?
-------------------------------
?
XML Layouts
?
XML布局
?
-------------------------------
?
In this document
?
本文目录
?
* Write the XML 书写XML
* Load the XML Resource 加载XML资源
* Attributes 属性
* ID 唯一标识符
* Layout Parameters 布局参数
* Position 位置
* Size, Padding and Margins 大小,内边距,外边距
?
Key classes
?
关键类
?
View
ViewGroup
ViewGroup.LayoutParams
?
-------------------------------
?
Your layout is the architecture for the user interface in an Activity. It defines the layout structure and holds all the elements that appear to the user. You can declare your layout in two ways:
?
你的布局是Activity对象中用户界面的架构。它定义布局结构并持有显示给用户的所有元素。你可以以两种方式声明你的布局:
?
* Declare UI elements in XML. Android provides a straightforward XML vocabulary that corresponds to the View classes and subclasses, such as those for widgets and layouts.
?
* 用XML声明用户界面元素。Android提供一种直观的XML词汇对应View类及其子类,诸如用于部件和布局的词汇。
?
* Instantiate layout elements at runtime. Your application can create View and ViewGroup objects (and manipulate their properties) programmatically.
?
* 在运行时实例化布局元素。你的应用程序可以用编程方式创建View和ViewGroup对象(并操纵它们的属性)
?
The Android framework gives you the flexibility to use either or both of these methods for declaring and managing your application's UI. For example, you could declare your application's default layouts in XML, including the screen elements that will appear in them and their properties. You could then add code in your application that would modify the state of the screen objects, including those declared in XML, at run time.
?
Android框架为你提供使用这两种方式以声明和管理你的应用程序用户界面的灵活性。例如,你可以用XML声明你的应用程序的默认布局,在它们和它们的属性中包括将显示的屏幕元素。然后你可以在你的应用程序中添加代码,在运行期间修改屏幕对象的状态,包括在XML中声明的对象。
?
-------------------------------
?
* The ADT Plugin for Eclipse offers a layout preview of your XML — with the XML file opened, select the Layout tab.
?
* Eclipse的ADT插件提供你的XML的布局预览——打开XML文件,选择布局标签。
?
* You should also try the Hierarchy Viewer tool, for debugging layouts — it reveals layout property values, draws wireframes with padding/margin indicators, and full rendered views while you debug on the emulator or device.
?
* 你还应该尝试层级查看器工具,以调试布局——它展开布局属性值,用内/外边距指示器绘画线框,以及当你在模拟器或设备上调试时完全渲染的视图。
?
* The layoutopt tool lets you quickly analyze your layouts and hierarchies for inefficiencies or other problems.
?
* layoutopt工具让你快速分析你的布局和层级的低效或其它问题。
?
-------------------------------
?
The advantage to declaring your UI in XML is that it enables you to better separate the presentation of your application from the code that controls its behavior. Your UI descriptions are external to your application code, which means that you can modify or adapt it without having to modify your source code and recompile. For example, you can create XML layouts for different screen orientations, different device screen sizes, and different languages. Additionally, declaring the layout in XML makes it easier to visualize the structure of your UI, so it's easier to debug problems. As such, this document focuses on teaching you how to declare your layout in XML. If you're interested in instantiating View objects at runtime, refer to the ViewGroup and View class references.
?
用XML声明你的用户界面的好处是让你能更好地分离你的应用程序的表现以及控制它的行为的代码。你的用户界面描述对于你的应用程序来说是外部的,这意味着你可以修改或适配它而不必修改你的源代码并重新编译。例如,你可以创建不同屏幕方向,不同设备屏幕大小,以及不同语言的XML布局。额外地,用XML声明布局简化了你的用户界面的可视化,所以它更容易调试问题。就这点而言,本文把焦点集中在教你如何用XML声明你的布局。如果你正感兴趣于在运行期实例化View对象,请参照ViewGroup和View的类参考手册。
?
In general, the XML vocabulary for declaring UI elements closely follows the structure and naming of the classes and methods, where element names correspond to class names and attribute names correspond to methods. In fact, the correspondence is often so direct that you can guess what XML attribute corresponds to a class method, or guess what class corresponds to a given xml element. However, note that not all vocabulary is identical. In some cases, there are slight naming differences. For example, the EditText element has a text attribute that corresponds to EditText.setText().
?
通常,声明用户界面元素的XML词汇紧密地遵循类和方法的结构和命名,元素名称对应类名而属性名称对应方法。事实上,这种符合经常是如此直接的,以至于你可以猜到什么XML属性对应类方法,或猜到什么类对应所给的xml元素。然而,注意不是所有词汇都是相同的。在某些情况下,有稍微的命名差异。例如,EditText元素拥有text属性,对应于EditText.setText()。
?
-------------------------------
?
Tip: Learn more about different layout types in Common Layout Objects. There are also a collection of tutorials on building various layouts in the Hello Views tutorial guide.
?
提示:请在一般布局对象章节中获取更多关于不同布局类型的信息。在Hello View教程指引中还有一些关于构建不同布局的教程。
?
-------------------------------
?
Write the XML
?
书写XML
?
-------------------------------
?
For your convenience, the API reference documentation for UI related classes lists the available XML attributes that correspond to the class methods, including inherited attributes.
?
为了你的方便,用户界面相关类的API参考文档列出可用的XML属性对应于类方法,包括继承属性。
?
To learn more about the available XML elements and attributes, as well as the format of the XML file, see Layout Resources.
?
为了获取更多关于可用XML元素和属性,以及XML文件的格式的信息,请参见布局资源章节。
?
-------------------------------
?
Using Android's XML vocabulary, you can quickly design UI layouts and the screen elements they contain, in the same way you create web pages in HTML — with a series of nested elements.
?
使用Android的XML词汇,你可以以你用HTML创建网页的相同方式,快速设计用户界面布局以及它们包含的屏幕元素——使用一系列嵌套的元素。
?
Each layout file must contain exactly one root element, which must be a View or ViewGroup object. Once you've defined the root element, you can add additional layout objects or widgets as child elements to gradually build a View hierarchy that defines your layout. For example, here's an XML layout that uses a vertical LinearLayout to hold a TextView and a Button:
?
每个布局文件必须准确包含一个根元素,它必须是View或ViewGroup对象。一旦你已经定义根元素,你就可以添加额外的布局对象或部件作为子元素以逐步构建定义你的布局的视图层级。例如,这里有一个XML布局,使用垂直LinearLayout以持有一个TextView和一个Button。
?
-------------------------------
?
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
? ? ? ? ? ? ? android:layout_width="fill_parent"?
? ? ? ? ? ? ? android:layout_height="fill_parent"?
? ? ? ? ? ? ? android:orientation="vertical" >
? ? <TextView android:id="@+id/text"
? ? ? ? ? ? ? android:layout_width="wrap_content"
? ? ? ? ? ? ? android:layout_height="wrap_content"
? ? ? ? ? ? ? android:text="Hello, I am a TextView" />
? ? <Button android:id="@+id/button"
? ? ? ? ? ? android:layout_width="wrap_content"
? ? ? ? ? ? android:layout_height="wrap_content"
? ? ? ? ? ? android:text="Hello, I am a Button" />
</LinearLayout>
?
-------------------------------
?
After you've declared your layout in XML, save the file with the .xml extension, in your Android project's res/layout/ directory, so it will properly compile.
?
在你已经用XML声明你的布局后,请保存文件为.xml扩展名,放在你的Android工程的res/layout/目录,使其能正确编译。
?
We'll discuss each of the attributes shown here a little later.
?
稍后我们将讨论展示在这里的每个属性。
?
-------------------------------
?
Load the XML Resource
?
加载XML资源
?
When you compile your application, each XML layout file is compiled into a View resource. You should load the layout resource from your application code, in your Activity.onCreate() callback implementation. Do so by calling setContentView(), passing it the reference to your layout resource in the form of: R.layout.layout_file_name For example, if your XML layout is saved as main_layout.xml, you would load it for your Activity like so:
?
当你编译你的应用程序时,每个XML布局文件被编译进一个View资源。你应该从你的应用程序代码,你的Activity.onCreate()回调实现中,加载布局资源。通过调用setContentView()来做到,把你的布局资源传递给它,格式为:R.layout.layout_file_name。例如,如果你的XML布局保存为main_layout.xml,你应该为你的Activity对象加载它,就像这样:
?
-------------------------------
?
public void onCreate(Bundle savedInstanceState) {
? ? super.onCreate(savedInstanceState);
? ? setContentView(R.layout.main_layout);
}
?
-------------------------------
?
The onCreate() callback method in your Activity is called by the Android framework when your Activity is launched (see the discussion about lifecycles, in the Activities document).
?
当你的Activity对象被启动时,你的Activity对象中的onCreate()回调方法被Android框架调用(参见活动文档中关于生命周期的讨论)。
?
Attributes
?
属性
?
Every View and ViewGroup object supports their own variety of XML attributes. Some attributes are specific to a View object (for example, TextView supports the textSize attribute), but these attributes are also inherited by any View objects that may extend this class. Some are common to all View objects, because they are inherited from the root View class (like the id attribute). And, other attributes are considered "layout parameters," which are attributes that describe certain layout orientations of the View object, as defined by that object's parent ViewGroup object.
?
每个View和ViewGroup对象支持它们自己各自的XML属性。一些属性特定于一个View对象(例如,TextView支持textSize属性),但这些属性还继承自可能扩展了这个类的任意View对象。有一些对于所有View对象是通用的,因为它们都继承自根View类(如id属性)。另外,其它属性被视为“布局参数”,它是描述视图对象的某个布局方向的属性,正如那个对象的父ViewGroup对象所定义的那样。
?
ID
?
唯一标识符
?
Any View object may have an integer ID associated with it, to uniquely identify the View within the tree. When the application is compiled, this ID is referenced as an integer, but the ID is typically assigned in the layout XML file as a string, in the id attribute. This is an XML attribute common to all View objects (defined by the View class) and you will use it very often. The syntax for an ID, inside an XML tag is:
?
任意View对象可以拥有一个与它关联的整数ID。在树中唯一地标识视图。当应用程序被编译时,这个ID被引用作为整数,但ID通常赋予在布局XML文件中作为字符串,放在id属性中。这是一个普遍针对所有View对象的XML属性(被View类定义),而你将经常使用它。在XML标签中,ID的语法是:
?
-------------------------------
?
android:id="@+id/my_button"
?
(注:@表示这里需要注入,+表示id自增,id/my_button表示在Java代码中的常数是<应用程序的包名>.R.id.my_button,可以传给Activity.findViewById())
?
-------------------------------
?
The at-symbol (@) at the beginning of the string indicates that the XML parser should parse and expand the rest of the ID string and identify it as an ID resource. The plus-symbol (+) means that this is a new resource name that must be created and added to our resources (in the R.java file). There are a number of other ID resources that are offered by the Android framework. When referencing an Android resource ID, you do not need the plus-symbol, but must add the android package namespace, like so:
?
字符串开头的@符号(@)表示XML解析器应该解析并展开ID字符串的其余部分并表示它作为ID资源。+号(+)表示这是一个新的资源名称,必须被创建和添加到我们的资源(在R.java文件中)。有一些其它的ID资源是由Android框架提供的。当引用Android资源ID时,你不需要加号,但必须添加Android包命名空间,就像这样:
?
-------------------------------
?
android:id="@android:id/empty"
?
-------------------------------
?
With the android package namespace in place, we're now referencing an ID from the android.R resources class, rather than the local resources class.
?
在合适的地方使用Android包命名空间,我们现在引用android.R资源类中一个ID,而非本地的资源类(注:本地的资源类是<包名>.R,是自动生成的)。
?
In order to create views and reference them from the application, a common pattern is to:
?
为了创建视图并从应用程序中引用它们,一般模式是:
?
1. Define a view/widget in the layout file and assign it a unique ID:
?
1. 在布局文件中定义一个视图/部件并赋予它一个唯一的ID:
?
-------------------------------
?
<Button android:id="@+id/my_button"
? ? ? ? android:layout_width="wrap_content"
? ? ? ? android:layout_height="wrap_content"
? ? ? ? android:text="@string/my_button_text"/>
?
-------------------------------
?
2. Then create an instance of the view object and capture it from the layout (typically in the onCreate() method):
?
2. 然后创建一个视图对象的实例并从布局中获取它(典型地在onCreate()方法中):
?
-------------------------------
?
Button myButton = (Button) findViewById(R.id.my_button);
?
-------------------------------
?
Defining IDs for view objects is important when creating a RelativeLayout. In a relative layout, sibling views can define their layout relative to another sibling view, which is referenced by the unique ID.
?
当创建一个RelativeLayout时,定义视图对象的ID是重要的。在相对布局中,兄弟视图可以相对于通过唯一的ID引用的另一个兄弟视图来定义它们的布局。
?
An ID need not be unique throughout the entire tree, but it should be unique within the part of the tree you are searching (which may often be the entire tree, so it's best to be completely unique when possible).
?
ID对于整棵树来说不需要唯一,但它应该在你所搜索的树的局部内唯一(它往往是整棵树,所以如果可能的话最好完全唯一)
?
Layout Parameters
?
布局参数
?
XML layout attributes named layout_something define layout parameters for the View that are appropriate for the ViewGroup in which it resides.
?
名为layout_something的XML布局属性定义视图的布局参数,适应它所处的ViewGroup。
?
Every ViewGroup class implements a nested class that extends ViewGroup.LayoutParams. This subclass contains property types that define the size and position for each child view, as appropriate for the view group. As you can see in figure 1, the parent view group defines layout parameters for each child view (including the child view group).
?
每个ViewGroup类实现一个扩展自ViewGroup.LayoutParams的内嵌类。这个子类包含属性类型,定义每个子视图的大小和位置,适应视图组。正如你在图1看到的那样,父视图组定义每个子视图(包括子视图组)的布局参数。
?
-------------------------------
?
(图略:
LinearLayout -> View + LinearLayout.LayoutParams
? ? ? ? ? ? ?-> View + LinearLayout.LayoutParams
? ? ? ? ? ? ?-> RelativeLayout + LinearLayout.LayoutParams
-> View + RelativeLayout.LayoutParams
-> View + RelativeLayout.LayoutParams
-> View + RelativeLayout.LayoutParams
)
?
Figure 1. Visualization of a view hierarchy with layout parameters associated with each view.
?
图1. 带有与每个视图关联的布局参数的视图层级的可视化。
?
-------------------------------
?
Note that every LayoutParams subclass has its own syntax for setting values. Each child element must define LayoutParams that are appropriate for its parent, though it may also define different LayoutParams for its own children.
?
注意每个LayoutParams子类拥有它自己的设置值语法。每个子元素必须定义LayoutParams适应它的父大小,虽然它还可以为它的子对象定义不同的LayoutParams。
?
All view groups include a width and height (layout_width and layout_height), and each view is required to define them. Many LayoutParams also include optional margins and borders.
?
所有视图组包括宽度和高度(layout_width和layout_height),并且每个视图都必须定义它们。许多LayoutParams还包含可选外边距和边线。
?
You can specify width and height with exact measurements, though you probably won't want to do this often. More often, you will use one of these constants to set the width or height:
?
你可以用精确的度量指定宽度和高度,虽然你很可能不希望经常做这种事。更常见的是,你将使用这些常量的其中一个设置宽度或高度:
?
* wrap_content tells your view to size itself to the dimensions required by its content
?
* wrap_content叫你的视图调整自身尺寸为它的内容所需的尺寸。
?
* fill_parent (renamed match_parent in API Level 8) tells your view to become as big as its parent view group will allow.
?
* fill_parent(在API级别8中更名为match_parent)叫你的视图变成和它的父视图组允许的相同大小。
?
In general, specifying a layout width and height using absolute units such as pixels is not recommended. Instead, using relative measurements such as density-independent pixel units (dp), wrap_content, or fill_parent, is a better approach, because it helps ensure that your application will display properly across a variety of device screen sizes. The accepted measurement types are defined in the Available Resources document.
?
通常,使用绝对单位诸如像素指定布局宽度和高度是不建议的。取而代之,使用相对度量诸如密度无关的像素单位(dp)(注:这里的dp和dpi貌似是无关的)或fill_parent是更好的方法,因为它有助于确保你的应用程序可以正确地跨不同种类的设备屏幕大小显示。接受的度量类型定义在可用资源文档中。
?
-------------------------------
?
Layout Position
?
布局位置
?
The geometry of a view is that of a rectangle. A view has a location, expressed as a pair of left and top coordinates, and two dimensions, expressed as a width and a height. The unit for location and dimensions is the pixel.
?
视图的集合信息是矩形范围。视图拥有位置,表现为一对左和上坐标,以及两个尺寸,表现为宽度和高度。位置和尺寸的单位为像素。
?
It is possible to retrieve the location of a view by invoking the methods getLeft() and getTop(). The former returns the left, or X, coordinate of the rectangle representing the view. The latter returns the top, or Y, coordinate of the rectangle representing the view. These methods both return the location of the view relative to its parent. For instance, when getLeft() returns 20, that means the view is located 20 pixels to the right of the left edge of its direct parent.
?
可以通过调用方法getLeft()和getTop()获取视图位置。前者返回代表视图矩形的左,或X,坐标。后者返回代表视图矩形的上,或Y,坐标。这些方法都返回视图相对于它的父对象的位置,例如,当getLeft()返回20时,意味着视图位于相对它直接父对象的左边缘以右的20像素处。
?
In addition, several convenience methods are offered to avoid unnecessary computations, namely getRight() and getBottom(). These methods return the coordinates of the right and bottom edges of the rectangle representing the view. For instance, calling getRight() is similar to the following computation: getLeft() + getWidth().
?
另外,提供一些便利方法避免不必要的计算,名称为getRight()和getBottom()。这些方法返回对于代表视图矩形的右边和下边边缘的坐标。例如,调用getRight()类似于以下计算:getLeft() + getWidth()。
?
-------------------------------
?
Size, Padding and Margins
?
大小,内边距和外边距
?
The size of a view is expressed with a width and a height. A view actually possess two pairs of width and height values.
?
视图的大小用宽度和高度表示。视图实际上拥有两对宽度和高度值。
?
The first pair is known as measured width and measured height. These dimensions define how big a view wants to be within its parent. The measured dimensions can be obtained by calling getMeasuredWidth() and getMeasuredHeight().
?
第一对被称为测量宽度和测量高度。这些尺寸定义一个视图希望它在它的父对象中有多大。度量尺寸可以通过调用getMeasuredWidth()和getMeasuredHeight()获取。
?
The second pair is simply known as width and height, or sometimes drawing width and drawing height. These dimensions define the actual size of the view on screen, at drawing time and after layout. These values may, but do not have to, be different from the measured width and height. The width and height can be obtained by calling getWidth() and getHeight().
?
第二对被简单地称为宽度和高度,或者有时称为绘画宽度和绘画高度。这些尺寸定义屏幕上视图的实际大小,在绘画期和布局后。这些值可以,但不一定,与测量宽度和高度不同。宽度和高度可以通过调用getWidth()和getHeight()获取。
?
To measure its dimensions, a view takes into account its padding. The padding is expressed in pixels for the left, top, right and bottom parts of the view. Padding can be used to offset the content of the view by a specific amount of pixels. For instance, a left padding of 2 will push the view's content by 2 pixels to the right of the left edge. Padding can be set using the setPadding(int, int, int, int) method and queried by calling getPaddingLeft(), getPaddingTop(), getPaddingRight() and getPaddingBottom().
?
为了测量它的尺寸,一个视图考虑它的内边距。内边距被表达为视图左上右下部分的像素单位大小。内边距可以用于偏移视图内容特定数量的像素。例如,左内边距值为2将把视图的内容推移到左边缘以右的2个像素。内边距可以使用setPadding(int, int, int, int)方法设置,并通过调用getPaddingLeft(),getPaddingTop(),getPaddingRight()和getPaddingBottom()查询。
?
Even though a view can define a padding, it does not provide any support for margins. However, view groups provide such a support. Refer to ViewGroup and ViewGroup.MarginLayoutParams for further information.
?
即便一个视图可以定义内边距,但是它不提供任何对外边距的支持。然而,视图组提供这样的支持。参考ViewGroup和ViewGroup.MarginLayoutParams以获取更多信息。
?
For more information about dimensions, see Dimension Values.
?
更多关于尺寸的信息,请参见尺寸值。
?
Except as noted, this content is licensed under Apache 2.0. For details and restrictions, see the Content License.
?
除特别说明外,本文在Apache 2.0下许可。细节和限制请参考内容许可证。
?
Android 4.0 r1 - 17 Nov 2011 21:59
Site Terms of Service - Privacy Policy - Brand Guidelines
?
-------------------------------
?
Portions of this page are modifications based on work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.
?
(此页部分内容基于Android开源项目,以及使用根据创作公共2.5来源许可证描述的条款进行修改)
?