android2.2官方开发手册(02-01)-Declaring Layout-设计布局

android2.2官方开发手册(02-01)-Declaring Layout-设计布局

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中的UI的结构。它定义了布局结构并持有所有用户能看到的元素。你可以有两种方式来定义你的布局:

  • 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中定义UI元素。 Android提供了一整套和各种View类对应的易懂的xml语法,例如各种widget和layout等。
  • Instantiate layout elements at runtime . Your application can create View and ViewGroup objects (and manipulate their properties) programmatically.
  • 在运行时初始化Layout元素。 你的应用程序可以使用代码创建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框架通过这两种方法并存的方式提供了灵活的UI定义方式。例如,你可以在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文件,并选择layout标签。
  • 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.
  • 你也可以尝试一下层次浏览器工具(在sdk/tools下),用来调试布局——它显示了布局属性值,根据画出线图来表示padding/margin以及渲染后的view的外观。
  • 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中定义UI的好处是它让你更好的将应用程序的外观和控制行为 的代码分开。你的UI描述在应用程序的代码之外,这意味着你可以在不修改代码和重新编译的前提下修改UI。例如,你可以为不同的屏幕朝向,不同的屏幕大小 和不同的语言设定不同的布局。另外,在xml中定义布局使得你的UI更加直观和容易调试(xml的结构比java代码更清晰)。本文介绍如何在xml中定 义布局。

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

总的来说,定义UI的xml词汇和相应的类名、方法名是紧密相关 的;xml的元素名对应类名,而xml的属性名对应方法名。事实上,它们之间的关系通常非常直接以至于你可以从xml属性名猜出方法名,或者从xml元素 猜出java类名。然而,注意不是所有的词汇都是相同的。在某情况下二者的命名有些小的区别。例如,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.

提示: Common Layout Objects一节中有关于不同布局类型的介绍。在Hello Views教程中也有一些关于创建不同的布局的教程。

Write the 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.

为了阅读的方便,UI相关类的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格式的信息相见Layout Resources一节。

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词汇,你可以很快设计UI布局和它包含的各种屏幕元素,就像使用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对象。一旦你定义了根元素,你就可以加入额外的布局对象或者widget作为其子元素,逐渐构成你的完整布局。例如,这里有一个使用从 上到下的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定义了布局之后,将它保存在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:

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 on Lifecycles, in the Application Fundamentals , for more on this).

再你的Activity中的onCreate()回调方法在你的Activity启动时被android框架调用。参见在Application Fundamentals中的声明周期

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属性)。还有的属性被认为是“布局参数”,用来描述View对象的布局属性。

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和它相关联,来在一棵树中唯一 的指定一个View对象。当应用程序被编译时,该id被当做一个整数处理,但是该ID一般是在布局xml里作为一个字符串出现,作为id属性的值。这是一 个所有View对象都有的xml属性(由View基类定义)。在xml标签中定义一个id的语法如下:

android:id="@+id/my_button"

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资源。+表示这是一个新的资源名称,必须将其加入我们的资源集(R.java)。有一些其它的ID资源是由 Android框架提供的,当引用它们时,不需要使用+符号,但必须加上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资源类的对象,而不是本地资源类中的对象。

In order to create views and reference them from the application, a common pattern is to:

为了创建view并从应用程序中引用它们,下面是一个基本的模式:

  1. Define a view/widget in the layout file and assign it a unique ID: 定义一个view/widget并给它分配一个唯一的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): 然后创建一个该View对象并从布局中得到它(一般在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.

为View对象定义id在创建RelativeLayout(相对布局)中是很重要的。在一个相对布局中,兄弟View(位于树结构的同一层的两节点)可以定义它们相互之间的的相对位置,这需要id来标识View对象。

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不需要在整个树中唯一,但它必须在你正在搜索的树的部分中唯一(常常就是整个树),因此最好尽量使用唯一的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布局属性,定义了一个View在它所在的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 the figure below, the parent view group defines layout parameters for each child view (including the child view group).

每个ViewGroup类实现一个嵌套类,该类是ViewGroup.LayoutParams的子类。该类包含了定义每个子View大小和位置的属性。如下图所示,父view group定义了子view的布局参数:

布局

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.

每个view group都包含一个宽度和高度(layout_width和layout_height),每个view必须定义它们。很多LayoutParams也包括可选的margin(空白)和border(边界)。

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:

你可以使用精确值来指定宽度和高度,尽管你可能很少这样使用。更常见 的是,你把view对象的大小设为和它的内容相合适,或者尽可能的大将其父对象填满(分别对应wrap_content和 fill_parent)。可接受的长度单位在Available Resources文档中。

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

总的来讲,定义layout的宽和高不建议使用绝对单位如像素。使用 相对的单位,如像素密度,wrap_content或者fill_parent,是更好的方法。因为这使得你的程序更适合在各个设备屏幕中显示。能够接受 的单位类型定义在Available Resources中。

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.

view的几何性质就是它所在矩形的几何性质。一个view的位置用一对left和top坐标表示,两个长度用width和height来表示。位置和长度的单位是像素。

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()可以得到一个View的位置。xxxx。这两个方法返回的是相对于其父元素的位置,例如,如果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.

一个view的大小使用宽度和高度来描述。一个view实际上有两组高度和宽度值。

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

第一组成为测量宽度和测量高度。这些长度定义了一个view希望在它的父view中的大小。测量长度可以使用getMesuredWidth()和 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() .

第二组为宽度和高度,有时被成为绘制宽度和绘制高度。这些长度定义了view在屏幕上绘制和布局时的实际大小。这些值可能和测量长度不同。它们可以通过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() .

为了测量它的面积,一个view将它的 padding考虑在内。padding使用像素来表示,可以设定上下左右各个方向上的padding。padding可以用来将view产生一个位移。 例如,一个2像素的左padding将使view相对于左边界向右偏移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.

虽然一个view可以定义一个padding,但它并不支持margin。view group支持margin。

For more information about dimensions, see Dimension Values .

↑ Go to top

← Back to User Interface

你可能感兴趣的:(android,xml,layout,application,resources,attributes)