原文地址:http://developer.android.com/training/basics/firstapp/building-ui.html
---------------------------------------------------------------------------------
The graphical user interface for an Android app is built using a hierarchy of View
and ViewGroup
objects. View
objects
are usually UI widgets such as buttons or text
fields and ViewGroup
objects
are invisible view containers that define how the child views are laid out, such as in a grid or a vertical list.
一个Android app的图形用户界面是使用 View
和 ViewGroup
对象的层次结构来建立的。
View
对象通常是一些UI部件,例如 buttons 或 text
fields ,而 ViewGroup
对象是一些不可见的容器,它们定义了子界面是如何排布的,例如在一个网格或一个垂直列表里。
Android provides an XML vocabulary that corresponds to the subclasses of View
and ViewGroup
so
you can define your UI in XML using a hierarchy of UI elements.
Android提供了一个XML词汇表,它对应了 View
和 ViewGroup
的子类,因此你可以在XML中使用UI元素的层次结构来定义你自己的UI。
Alternative Layouts
Declaring your UI layout in XML rather than runtime code is useful for several reasons, but it's especially important so you can create different layouts for different screen sizes. For example, you can create two versions of a layout and tell the system to use one on "small" screens and the other on "large" screens. For more information, see the class about Supporting Different Devices.
可供选择的布局
在XML中声明你的UI布局,而非运行时刻的代码中,在一些时候是有用的,尤其是你可以为不同的屏幕大小创建不同的布局。例如,你可以创建两个版本的同一布局,然后告诉系统,在“小”屏幕上使用其中一个,而在“大”屏幕上使用另一个。更多的信息,请见Supporting Different Devices一课。
In this lesson, you'll create a layout in XML that includes a text field and a button. In the following lesson, you'll respond when the button is pressed by sending the content of the text field to another activity.
在这节课中,你将在XML中创建一个布局,它包含了一个文字区域和一个按键。在下面的课程中,在按键被按下时,你将会通过向另一个activity发送文字编辑域中的内容来做出响应。
Create a Linear Layout —— 创建一个线性布局
Open the activity_main.xml
file from the res/layout/
directory.
打开 res/layout/
目录下的activity_main.xml文件。
Note: In Eclipse, when you open a layout file, you’re first shown the Graphical Layout editor. This is an editor that helps you build layouts using WYSIWYG tools. For this lesson, you’re going to work directly with the XML, so click the activity_main.xml tab at the bottom of the screen to open the XML editor.
注意:在Eclipse里,当你打开一个布局文件时,你最先看到的是布局编辑器的图形界面。这个编辑器帮助你使用WYSIWYG来建立布局。在本节课,你将直接用XML工作,因此点击屏幕底部的 activity_main.xml 标签来打开XML编辑器。
The BlankActivity template you chose when you created this project includes the activity_main.xml
file with a RelativeLayout
root
view and a TextView
child
view.
在你创建这个项目时选择的 BlankActivity 模板包含了 activity_main.xml
文件,包括一个 RelativeLayout
根视图以及一个 TextView
子视图。
First, delete the <TextView>
element
and change the <RelativeLayout>
element
to <LinearLayout>
.
Then add the android:orientation
attribute
and set it to "horizontal"
. The result looks like this:
首先,删除 <TextView>
元素,并将 <RelativeLayout>
元素改为 <LinearLayout>。然后添加 android:orientation
属性,并将它设置为"horizontal"。结果如下:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" > </LinearLayout>
LinearLayout
is
a view group (a subclass of ViewGroup
)
that lays out child views in either a vertical or horizontal orientation, as specified by the android:orientation
attribute.
Each child of a LinearLayout
appears
on the screen in the order in which it appears in the XML.
LinearLayout
是一个视图集合(ViewGroup的一个子类
),它使用水平或垂直的布局来排布子视图,正如 android:orientation
属性中设置的那样。LinearLayout的每个子视图按照它们在XML中出现的顺序显示在屏幕上。
The other two attributes, android:layout_width
and android:layout_height
,
are required for all views in order to specify their size.
另外两个属性,android:layout_width
和 android:layout_height
,是所有视图都需要的以便指明它们的大小。
Because the LinearLayout
is
the root view in the layout, it should fill the entire screen area that's available to the app by setting the width and height to "match_parent"
. This value
declares that the view should expand its width or height to match the width or height of the parent view.
因为LinearLayout是这个布局的子视图,它应该填充整个可用的屏幕区域,这通过设置长宽值为"match_parent"来实现。这个值表明该视图应该扩展它的长或宽来匹配父视图的长或宽。
For more information about layout properties, see the Layout guide.
更多有关布局性质的信息请见布局指南。
Add a Text Field —— 添加一个文本框
To create a user-editable text field, add an <EditText>
element
inside the <LinearLayout>
.
为了创建一个用户可编辑的文本框,向<LinearLayout>添加 <EditText>
元素。
Like every View
object, you
must define certain XML attributes to specify the EditText
object's
properties. Here’s how you should declare it inside the <LinearLayout>
element:
和每个View对象相同,你必须定义确定的XML属性来指定
EditText
对象的性质。下面展示了你应该如何在<LinearLayout>元素里声明它。
<EditText android:id="@+id/edit_message" android:layout_width="wrap_content" android:layout_height="wrap_content" android:hint="@string/edit_message" />
About resource objects
A resource object is simply a unique integer name that's associated with an app resource, such as a bitmap, layout file, or string.
Every resource has a corresponding resource object defined in your project's gen/R.java
file. You can use the object names in the R
class
to refer to your resources, such as when you need to specify a string value for the android:hint
attribute.
You can also create arbitrary resource IDs that you associate with a view using the android:id
attribute,
which allows you to reference that view from other code.
The SDK tools generate the R.java
each time you compile your app. You should never modify this file by hand.
For more information, read the guide to Providing Resources.
关于资源对象
一个资源对象只是一个唯一的整型名字,并与一个app资源相关联,例如一个位图,布局文件,或字符串。
每个资源都有一个对应的资源对象在你项目的 gen/R.java
文件中。你可以使用
R 类来引用你的资源,例如当你需要为 android:hint
属性指定一个字符串值。你也可以使用 android:id
属性创建任意的资源IDs并与一个视图相关联,这允许你在其他代码中引用这个视图。
每当你编译你的app时,SDK工具就会生成R.java。你不应该手动修改该文件。
更多信息请阅读Providing Resources指南。
About these attributes:
关于这些性质:
android:id
-
This provides a unique identifier for the view, which you can use to reference the object from your app code, such as to read and manipulate the object (you'll see this in the next lesson).
这个为该视图提供了一个唯一的标识符,你可以在你的app代码中使用它来引用这个对象,例如用于读取并操作该对象(在下一节课中你将会看到)。
The at sign (
@
) is required when you're referring to any resource object from XML. It is followed by the resource type (id
in this case), a slash, then the resource name (edit_message
).当你从XML文件中引用任意资源时,你需要at符号(@)。紧跟着的是该资源类型(本例中是
id
),一个斜杠,然后是该资源的名称(edit_message)。The plus sign (
+
) before the resource type is needed only when you're defining a resource ID for the first time. When you compile the app, the SDK tools use the ID name to create a new resource ID in your project'sgen/R.java
file that refers to theEditText
element. Once the resource ID is declared once this way, other references to the ID do not need the plus sign. Using the plus sign is necessary only when specifying a new resource ID and not needed for concrete resources such as strings or layouts. See the sidebox for more information about resource objects.资源类型前面的加号(
+
)只有在你第一次定义一个资源ID时才需要。当你编译这个app时,SDK工具使用这个ID名字在你的项目的gen/R.java
文件里,来创建一个新的资源ID并指向EditText
元素。一旦这个资源ID通过这种方式被声明,其他对这个ID的引用就不再需要加号。当且仅当定义一个新的资源ID时使用加号,对于具体的资源,例如字符串或布局则是不需要的。关于资源对象的更多信息,请见旁边的方框。 android:layout_width
andandroid:layout_height
- Instead of using specific sizes for the width and height, the
"wrap_content"
value specifies that the view should be only as big as needed to fit the contents of the view. If you were to instead use"match_parent"
, then theEditText
element would fill the screen, because it would match the size of the parentLinearLayout
. For more information, see the Layouts guide. 不是使用特定的长宽大小,"wrap_content"值指定了视图大小应该恰好适应视图内容。如果你使用"match_parent",那么EditText
将会填充屏幕,因为它要匹配父视图LinearLayout的大小。更多信息请见布局指南。 android:hint
- This is a default string to display when the text field is empty. Instead of using a hard-coded string as the value, the
"@string/edit_message"
value refers to a string resource defined in a separate file. Because this refers to a concrete resource (not just an identifier), it does not need the plus sign. However, because you haven't defined the string resource yet, you’ll see a compiler error at first. You'll fix this in the next section by defining the string. 当文本框为空时的默认文字。不是使用一个死的字符串作为该值,"@string/edit_message"引用了一个单独的文件中定义的一个字符串。因为这个引用了一个具体的资源(而不仅仅是一个标识符),它不需要加号。但是,因为你还没有定义这个字符串,你一开始将会看到一个编译错误。在下一章节中通过定义这个字符串,你将会纠正这个错误。Note: This string resource has the same name as the element ID:
edit_message
. However, references to resources are always scoped by the resource type (such asid
orstring
), so using the same name does not cause collisions.注意:这个字符串资源和元素ID有着相同的名字:edit_message。然而,资源的引用总是按资源类型来区分(例如
id
或string
),因此使用同一个名字不会引起冲突。
Add String Resources —— 添加字符串资源
When you need to add text in the user interface, you should always specify each string as a resource. String resources allow you to manage all UI text in a single location, which makes it easier to find and update text. Externalizing the strings also allows you to localize your app to different languages by providing alternative definitions for each string resource.
当你需要在用户界面中添加文字时,你应该总是将每个字符串指定为一个资源。字符串资源允许你在一个单独的位置管理所有的UI文本,这使得查找和更新文本变得更加容易。外化字符串也允许你通过提供可供选择的字符串资源,来支持不同的语言。
By default, your Android project includes a string resource file at res/values/strings.xml
. Add a new string named "edit_message"
and
set the value to "Enter a message." (You can delete the "hello_world" string.)
默认下,你的Android项目res/values/strings.xml下包含了一个字符串资源文件。添加一个名为"edit_message"的新的字符串,并将值设为"Enter a message"。(你可以删除"hello_world"字符串了。)
While you’re in this file, also add a "Send" string for the button you’ll soon add, called "button_send"
.
当你编辑该文件时,同时为你将要添加的按键添加一个"Send"字符串,叫做"button_send"。
The result for strings.xml
looks like this:
strings.xml
的结果如下:
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">My First App</string> <string name="edit_message">Enter a message</string> <string name="button_send">Send</string> <string name="menu_settings">Settings</string> <string name="title_activity_main">MainActivity</string> </resources>
For more information about using string resources to localize your app for other languages, see the Supporting Different Devices class.
关于使用字符串资源来本地化你的app适应其它语言的信息,请见 Supporting Different Devices 一课。
Add a Button —— 添加一个按键
Now add a <Button>
to
the layout, immediately following the <EditText>
element:
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/button_send" />
The height and width are set to "wrap_content"
so the button is only as big as necessary to fit the button's text. This button doesn't need the android:id
attribute,
because it won't be referenced from the activity code.
Make the Input Box Fill in the Screen Width
The layout is currently designed so that both the EditText
and Button
widgets
are only as big as necessary to fit their content, as shown in figure 2.
当前设计的布局中,EditText
和 Button
部件的大小刚好适应它们的内容,正如图2中显示的一样。
This works fine for the button, but not as well for the text field, because the user might type something longer. So, it would be nice to fill the unused screen width with the text field. You can do this inside a LinearLayout
with
the weight property, which you can specify using the android:layout_weight
attribute.
这对于按键很适用,但却不适合文本框,因为用户可能键入更长的内容。因此,应该使用文本框来填充剩余的未被适用的屏幕宽度。你可以在LinearLayout中使用weight 属性来做到这点,你可以指定android:layout_weight的属性。
The weight value is a number that specifies the amount of remaining space each view should consume, relative to the amount consumed by sibling views. This works kind of like the amount of ingredients in a drink recipe: "2 parts vodka, 1 part coffee liqueur" means two-thirds of the drink is vodka. For example, if you give one view a weight of 2 and another one a weight of 1, the sum is 3, so the first view fills 2/3 of the remaining space and the second view fills the rest. If you add a third view and give it a weight of 1, then the first view (with weight of 2) now gets 1/2 the remaining space, while the remaining two each get 1/4.
weight值指定了每个视图占据的剩余空间的数量,相对于兄弟视图的占据量。这和一杯饮料食谱中的原料分量相似:“2分伏特加,一份咖啡甜酒”意味着三分之二的饮料是伏特加。例如,如果你给一个视图的分量为2,另一个分量是1,那么和是3,因此第一个视图将填充剩余空间的2/3,而第二个视图填充剩下的空间。如果你添加第三个视图,并赋予它的分量为1,那么第一个视图(分量为2)现在将得到1/2的剩余空间,而剩下的两个每个占据1/4.
The default weight for all views is 0, so if you specify any weight value greater than 0 to only one view, then that view fills whatever space remains after all views are given the space they require. So, to fill the remaining space in your layout with the EditText
element,
give it a weight of 1 and leave the button with no weight.
默认的所有视图的分量为0,因此如果你只为一个视图指定任何大于0的分量值,那么在所有视图被寄予需要的空间后,该视图将会占据剩余所有空间。因此,在你的布局中为了让EditText元素占据剩余空间,赋予它分量值为1,并保留按键无分量值。
<EditText android:layout_weight="1" ... />
In order to improve the layout efficiency when you specify the weight, you should change the width of the EditText
to
be zero (0dp). Setting the width to zero improves layout performance because using "wrap_content"
as the width requires the system to calculate a width that
is ultimately irrelevant because the weight value requires another width calculation to fill the remaining space.
当你指定分量值时为了提高布局的效率,你应该改变EditText的宽度值为0(0dp)。将宽度设置为0将会提高布局的性能,因为使用g"wrap_content"
作为宽度将会要求系统最终计算一个无关的宽度因为分量值要求另一个宽度计算来填充剩余空间。
<EditText android:layout_weight="1" android:layout_width="0dp" ... />
Figure 3 shows the result when you assign all weight to the EditText
element.
图3展示了当你为 EditText
元素设定所有分量值后的结果。
Here’s how your complete layout file should now look:
下面是完整布局文件:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"> <EditText android:id="@+id/edit_message" android:layout_weight="1" android:layout_width="0dp" android:layout_height="wrap_content" android:hint="@string/edit_message" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/button_send" /> </LinearLayout>
This layout is applied by the default Activity
class
that the SDK tools generated when you created the project, so you can now run the app to see the results:
该布局应用于默认的 Activity
类,它是在你创建项目时由SDK工具生成的,因此你现在可以运行app来看到结果了:
- In Eclipse, click Run from the toolbar. 在Eclipse里,点击工具栏中的Run 。
- Or from a command line, change directories to the root of your Android project and execute: 或者在命令行中,改变目录到你的Android项目的根目录,并执行:
ant debug adb install bin/MyFirstApp-debug.apk
Continue to the next lesson to learn how you can respond to button presses, read content from the text field, start another activity, and more.
下一节课你会学习如何响应按键的点击事件,从文本框中读取内容,开始另一个activity,以及更多的内容。