Android官方教程翻译(3)——创建一个简单的用户界面

转载请注明出处:http://blog.csdn.net/dawanganban/article/details/9839523

Building a Simple User Interface

创建一个简单的用户界面

PREVIOUSNEXT

THIS LESSON TEACHES YOU TO

这节课教你

1.    Create a Linear Layout

创建线性布局

2.    Add a Text Field

添加文本域

3.    Add String Resources

添加String资源文件

4.    Add a Button

添加一个按钮

5.    Make the Input Box Fill
in the Screen Width

创建一个输入框填满整个屏幕宽度

YOU SHOULD ALSO READ

·       Layouts

The graphical user interface for an Android app is builtusing a hierarchy of View and ViewGroup objects. View objects
are usually UI widgets such as buttons or text
fields
 and ViewGroupobjects
are invisible view containers that define how thechild views are laid out, such as in a grid or a vertical list.

Adroid的所有UI组件都是建立在View和ViewGroup的基础上的,如View 按钮text
fields
 和定义子视图的布局的ViewGroup对象。

Android采用了“组合器”设计模式来设计View和ViewGroup:ViewGroup是View的子类,因此ViewGroup也可以当成View使用。对于一个Android应用的图形用户界面来说,ViewGroup作为容器来盛装其他组件,而ViewGroup里除了可以包含普通的Viwe组件之外,还可以再次包含ViewGroup组件。

Android provides an XML vocabulary that corresponds tothe subclasses of View and ViewGroup so
you can define your UI in XML using a hierarchy of UIelements.

Android提供了一个XML词汇表对应ViewViewGroup的子类,这样你就可以在XML中使用的UI元素层次结构中定义的UI。

Alternative Layouts

Declaring your UI layout in XML rather than runtime codeis useful for several reasons, but it's especially important so you can createdifferent layouts for different screen sizes. For example, you can create twoversions
of a layout and tell the system to use one on "small"screens and the other on "large" screens. For more information, seethe class about Supporting
Different Devices
.

大意:Android应用推荐使用XML布局文件来定义用户界面,而不是使用java代码来开发用户界面。可以为不同大小屏幕开发不同的xml文件,这样就比较灵活。

Android官方教程翻译(3)——创建一个简单的用户界面

Figure 1. Illustration of how ViewGroup objects
form branches in the layout and contain other View objects.

In this lesson, you'll create a layout in XML thatincludes a text field and a button. In the following lesson, you'll respondwhen the button is pressed by sending the content of the text field to anotheractivity.

在本课中,您将创建一个XML中包含一个文本字段和一个按钮的布局。 在下面的课程,当按钮被按下文本字段中的内容发送到另一个activity。

Create a Linear Layout


Open the activity_main.xml file from the res/layout/ directory.

activity_main.xml res/layout/目录打开的activity_main.xml文件

Note: In Eclipse, when you open a layout file, you’re firstshown the Graphical Layout editor. This is an editor that helps you
buildlayouts using WYSIWYG tools. For this lesson, you’re going to work directlywith the XML, so click the activity_main.xml tab at the bottom of the screen to open the XML editor.

注:在Eclipse中,当你打开一个布局文件,第一次显示的是图形布局编辑器。 这是一个帮助您构建布局使用图形化工具编辑器。 在这一课中,你会直接使用XML,所以点击activity_main.xml屏幕底部标签打开XML编辑器。

The BlankActivity template you chose when you createdthis project includes the activity_main.xml file
with aRelativeLayout 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 theandroid: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"?>

<LinearLayoutxmlns: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 orhorizontal orientation, as specified by the android:orientation attribute.
Each child of a LinearLayout appears
on the screen in the order in which it appears inthe XML.

The other two attributes, android:layout_width and android:layout_height,are
required for all views in order to specify their size.

Because the LinearLayout is
the root view in the layout, it should fill the entirescreen area that's available to the app by setting the width and height to "match_parent". This value
declares that the view should expand itswidth or height to match the width or height of the parent view.

For more information about layout properties, see the Layout guide.

LinearLayout视图组( ViewGroup一个子类)是在任何一个垂直或水平方向的子视图android:orientation属性。表示 每一个LinearLayout子元素出现在屏幕上的顺序为垂直排列。

其他两个属性, android:layout_widthandroid:layout_height ,都需要对所有的视图指定它们的大小。

因为LinearLayout是在布局中的根视图,它应该填补"match_parent"通过设定应用程序可在的整个屏幕区域的宽度和高度的。 此值声明视图应该扩大它的宽度或高度与父视图的宽度或高度匹配 。

对于布局属性的更多信息,请参阅“ 布局指南。

Add a Text Field


To create a user-editable text field, add an <EditText> element
inside the <LinearLayout>.

Like every View object,
you must define certain XML attributes to specifythe EditText object's
properties. Here’s how you should declare itinside the <LinearLayout> element:

向<LinearLayout>中添加<EditText>元素

像每一个View对象,你必须定义某些XML属性指定的EditText对象的性质。

<EditTextandroid: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'sassociated with an app resource, such as a bitmap, layout file, or string.

资源对象仅仅是一个独特的整数名称相关联的应用程序资源,如位图,布局文件或字符串。

Every resource has a corresponding resource objectdefined 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 needto specify a string value
for theandroid:hint attribute.
You can also create arbitrary resource IDsthat you associate with a view using theandroid:id attribute,
which allows you to reference that view fromother code.

每个资源都有一个相应的资源在项目的gen/R.java文件定义的对象。 您可以使用的R类中的对象名称来指给你的资源,如当你需要android:hint属性指定一个字符串值。 您还可以创建任意的资源ID,关联到一个视图中使用的android:id属性,它允许你从其他代码中来引用该​​视图。

The SDK tools generate the R.javaeach time you compile your app. You should never modifythis file by hand.

每次编译您的应用程序时该SDK工具生成R.java。 您永远不应该去手动修改这个文件。

For more information, read the guide toProviding Resources.

欲了解更多信息,请阅读本指南提供了资源 。

About these attributes:

关于这些属性:

android:id

This provides a unique identifier for the view, which youcan use to reference the object from your app code, such as to read andmanipulate the object (you'll see this in the next lesson).

The at sign (@) is required when you're referring to any resourceobject from XML. It is followed by the resource type (id in
this case), a slash, then the resource name (edit_message).

The plus sign (+) before the resource type is needed only when you'redefining a resource ID for the first time. When you compile the app, the SDKtools
use the ID name to create a new resource ID in your project's gen/R.java file that refers to the EditText 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 isnecessary only when specifying a new resource ID and not needed for concrete resourcessuch as strings or layouts. See the sidebox for
more information about resourceobjects.

大意:这提供了一个独特的标识符,可以用它来引用该对象

android:layout_width and android:layout_height

Instead of using specific sizes for the width and height,the"wrap_content" valuespecifies that the view should
be only as big as needed to fit the contents ofthe view. If you were to instead use "match_parent", then the EditText element
would fill the screen, because it would match thesize of the parent LinearLayout.
For more information, see the Layouts guide.

"wrap_content"值,根据需要填充而不是使用特定尺寸的宽度和高度指定视图,以适应的内容的视图。 EditText元素将填充整个屏幕,因为它相对于LinearLayout是match_parent的 。 欲了解更多信息,请参阅布局指南。

android:hint

This is a default string to display when the text fieldis empty. Instead of using a hard-coded string as the value, the "@string/edit_message" value
refers to a string resource defined in a separatefile. Because this refers to a concrete resource (not just an identifier), itdoes not need the plus sign. However, because you haven't defined the stringresource yet, you’ll see a compiler error at first. You'll
fix this in the nextsection 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 bythe resource type (such as id or string),
so using the same name does not cause collisions.

注意:这个字符串资源具有相同的名称作为元素ID: edit_message。然而,引用资源是根据资源类型引用的,所以相同的名字不会引起冲突。

Add String Resources

添加字符串资源


When you need to add text in the user interface, youshould always specify each string as a resource. String resources allow you tomanage all UI text in a single location, which makes it easier to find andupdate text.
Externalizing the strings also allows you to localize your app todifferent languages by providing alternative definitions for each stringresource.

当你需要在用户界面中添加文本,你应该指定字符串作为一个资源。字符串资可以方便的管理所有UI文本,这样更容易找到资源并方便的更新文本。可以为不同的语言环境提供不同的字符串资源的定义文件。

By default, your Android project includes a stringresource file at res/values/strings.xml. Add a new string
named "edit_message" and set the value to "Enter a message." (Youcan 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".

当你在这个文件中添加一个“发送”字符串名字 "button_send"作为按钮的文本,他会马上被创建成对象供你使用。

The result for strings.xml looks like this:

String.xml的内容如下:

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

<resources>

<stringname="app_name">My First App</string>

<stringname="edit_message">Enter a message</string>

<stringname="button_send">Send</string>

<stringname="action_settings">Settings</string>

<stringname="title_activity_main">MainActivity</string>

</resources>

For more information about using string resources tolocalize your app for other languages, see the Supporting
Different Devices
 class.

关于更多的关于其他语言环境的字符串资源创建,请阅读Supporting
Different Devices
 一课。

Add a Button

添加一个按钮


Now add a <Button> to
the layout, immediately following the <EditText> element:

现在添加一个<Button>给布局文件。

<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 thebutton's text. This button doesn't need the android:id attribute,
because it won't be referenced from theactivity code.

按钮元素的高度和宽度设置为"wrap_content" ,这样按钮大小就是它的实际需要的大小。这个按钮元素不需要android:id 属性,因为它不用在activity代码中被引用。

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 theircontent, as shown in figure 2.

这样去设置布局文件可以使 EditText 和Button宽度以他所需要的合适宽度去填充,如图2所示。

Android官方教程翻译(3)——创建一个简单的用户界面

Figure 2. The EditText and Button widgets
have their widths set to "wrap_content".

This works fine for the button, but not as well for thetext field, because the user might type something longer. So, it would be niceto 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中设置权重属性,

使用android:layout_weight属性。

The weight value is a number that specifies the amount ofremaining space each view should consume, relative to the amount consumed bysibling views. This works kind of like the amount of ingredients in a drinkrecipe:
"2 parts vodka, 1 part coffee liqueur" means two-thirds ofthe drink is vodka. For example, if you give one view a weight of 2 and anotherone a weight of 1, the sum is 3, so the first view fills 2/3 of the remainingspace and the second view fills the rest.
If you add a third view and give it aweight of 1, then the first view (with weight of 2) now gets 1/2 the remainingspace, while the remaining two each get 1/4.

权重值是一个指定每个剩余视图应该划分的大小的量度。这就有点像配置饮料:例如,如果一个视图的权重为2而另一个视图的权重为1,总数为3,第一个视图就填补2/3而第二个视图填补剩下的1/3.如果再添加一个视图并让它的权重为1,这样第一个视图就填补1/2的剩余空间,而其余两个则分别填补剩余空间的1/4.

The default weight for all views is 0, so if you specifyany weight value greater than 0 to only one view, then that view fills whateverspace remains after all views are given the space they require. So, to fill theremaining
space in your layout with the EditText element,
give it a weight of 1 and leave the button withno weight.

视图默认的权重是0,所以如果你指定一个大于0的权重给一个视图,这个视图会填充所有的剩余空间。

<EditText

android:layout_weight="1"

... />

In order to improve the layout efficiency when youspecify the weight, you should change the width of theEditText to
be zero (0dp). Setting the width to zero improveslayout performance because using "wrap_content"as the width requires the system to calculate a widththat
is ultimately irrelevant because the weight value requires another widthcalculation to fill the remaining space.

当你指定权重时为了提高布局效率,你应该设置EditText的”wrap_content”属性为0dp.因为使用“wrap_content”作为宽度布局系统要去计算无用的宽度,权重使用的是另外一种计算方式去填充剩余空间。

<EditText

android:layout_weight="1"

android:layout_width="0dp"

... />

Figure 3 shows the result when you assign all weight tothe EditText element.

设置权重后的结果如图3所示。

Android官方教程翻译(3)——创建一个简单的用户界面

Figure 3. The EditText widget
is given all the layout weight, so fills theremaining space in the LinearLayout.

Here’s how your complete layout file should now look:

这里是完整的布局文件

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

<LinearLayoutxmlns: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">

<EditTextandroid: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 theproject, so you can now run the app to see the results:

这个布局文件默认添加到创建工程的时候默认生成的Activity类中。现在可以运行程序去看结果。

In Eclipse, click Run  from the toolbar.

在Eclipse中点击工具栏的Run按钮。

·        Or from acommand line, change directories to the root of your Android project andexecute:

·        或者从命令行,改变目录到应用程序的工程目录下并执行命令:

·        ant debug

·        adb install bin/MyFirstApp-debug.apk

Continue to the next lesson to learn how you can respondto button presses, read content from the text field, start another activity,and more.

下来将学习如何响应按钮点击事件,从文本域中读取内容,开启另一个activity。。。。

练习:

activity_main.xml

使用了一个文本域和两个按钮,其中一个按钮是自适应,另一个按钮占剩余空间的1/3,文本占剩余空间的2/3

<?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="2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="@string/edit_message" />
<Button
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="@string/button_cancel"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_send" />
</LinearLayout>

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="button_cancel">Cancel</string>
<string name="action_settings">Settings</string>
<string name="title_activity_main">MainActivity</string>
</resources>

MainActivity.java

package com.example.myfirstapp;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu; public class MainActivity extends Activity { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}

运行结果

Android官方教程翻译(3)——创建一个简单的用户界面

上一篇:Sql Server 常用的查询


下一篇:Visual C++编程命名规则