`
从此醉
  • 浏览: 1040867 次
  • 性别: Icon_minigender_1
  • 来自: US
社区版块
存档分类
最新评论

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 ofViewandViewGroupobjects.Viewobjects are usually UI widgets such asbuttonsortext fieldsandViewGroupobjects are invisible view containers that define how thechild views are laid out, such as in a grid or a vertical list.

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

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

Android provides an XML vocabulary that corresponds tothe subclasses ofViewandViewGroupso 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 aboutSupporting Different Devices.

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


Figure 1.Illustration of howViewGroupobjects form branches in the layout and contain otherViewobjects.

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 theactivity_main.xmlfile from theres/layout/directory.

activity_main.xmlres/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 theactivity_main.xmltab 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 theactivity_main.xmlfile with aRelativeLayoutroot view and aTextViewchild view.

当你创造了这个项目时,你选择的的BlankActivity模板包括activity_main.xml文件与一个RelativeLayout根观点和一个TextView子视图。

First, delete the<TextView>element and change the<RelativeLayout>element to<LinearLayout>. Then add theandroid:orientationattribute 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>

LinearLayoutis a view group (a subclass ofViewGroup) that lays out child views in either a vertical orhorizontal orientation, as specified by theandroid:orientationattribute. Each child of aLinearLayoutappears on the screen in the order in which it appears inthe XML.

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

Because theLinearLayoutis 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 tomatchthe width or height of the parent view.

For more information about layout properties, see theLayoutguide.

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 everyViewobject, you must define certain XML attributes to specifytheEditTextobject'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'sgen/R.javafile. You can use the object names in theRclass to refer to your resources, such as when you needto specify a string value for theandroid:hintattribute. You can also create arbitrary resource IDsthat you associate with a view using theandroid:idattribute, which allows you to reference that view fromother code.

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

The SDK tools generate theR.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 (idin 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'sgen/R.javafile that refers to theEditTextelement. 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_widthandandroid: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 theEditTextelement would fill the screen, because it would match thesize of the parentLinearLayout. For more information, see theLayoutsguide.

"wrap_content"值,根据需要填充而不是使用特定尺寸的宽度和高度指定视图,以适应的内容的视图。EditText元素将填充整个屏幕,因为它相对于LinearLayoutmatch_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 asidorstring), 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 atres/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 forstrings.xmllooks 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 theSupporting Different Devicesclass.

关于更多的关于其他语言环境的字符串资源创建,请阅读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 theandroid:idattribute, 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 theEditTextandButtonwidgets are only as big as necessary to fit theircontent, as shown in figure 2.

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


Figure 2.TheEditTextandButtonwidgets 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 aLinearLayoutwith theweightproperty, which you can specify using theandroid:layout_weightattribute.

这样做对按钮很合适,但是对文本可能还不太好,因为用户也许会输入很长的文字。所以最好让文本域填充满剩下的所有宽度。你可以在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 theEditTextelement, 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 theEditTextto 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 totheEditTextelement.

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


Figure 3.TheEditTextwidget is given all the layout weight, so fills theremaining space in theLinearLayout.

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 defaultActivityclass that the SDK tools generated when you created theproject, so you can now run the app to see the results:

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

In Eclipse, click Runfrom 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开发——简易计算器的设计报告.doc

    Android基于Linux平台,由操作系统、中间件、用户界面和应用软件组成,具 有以下5个特点:开放性、应用程序无界限、应用程序是在平等条件下创建的、应用程序 可以轻松的嵌入网络、应用程序可以并行运行。 一、实训...

    新版Android开发教程.rar

    也有分析认为,谷歌并不想做一个简单的手机终端制造商或者软件平台开发商,而意在一统传统互联网和 移 动互联网。----------------------------------- Android 编程基础 4 Android Android Android Android 手机新...

    老罗android开发视频教程全集百度网盘下载

    Android以Java为编程语言,使接口到功能,都有层出不穷的变化,其中Activity等同于J2ME的MIDlet,一个 Activity 类(class)负责创建视窗(window),一个活动中的Activity就是在 foreground(前景)模式,背景运行...

    Google Android SDK开发范例大全(PDF高清完整版3)(4-3)

    第3章 用户人机界面 3.1 更改与显示文字标签——TextView标签的使用 3.2 更改手机窗口画面底色——drawable定义颜色常数的方法 3.3 更改TextView文字颜色——引用Drawable颜色常数及背景色 3.4 置换TextView文字——...

    android开发入门教程

    9.1.2 用Intent启动一个新的Activity 9.1.3 Intent详细讲解 9.1.4 Android解析Intent实现 9.2 用广播告诉你——利用Intent来广播(BroadCast)事件 9.2.1 实现Android中的广播事件 9.2.2 BroadCastReceiver介绍 9.3 ...

    Android从入门到放弃—— 一、Activity详解1

    Activity作为Andorid的四大组件之一,为用户提供了一个界面,即我们能看到的界面。相当于一张画画用的纸,我们可以在上面画任何我们想要的内容。 Activity的创建: 就像我们画画需要拿一张画纸铺在画板上一样,想要...

    Android应用开发详解

    Android 应用案例——雷电游戏,通过一个完整的雷电游戏,讲述了Android的游戏开发思路、框架和具体实现,并比较了Android游戏开发和Java ME游戏开发的异同,成功移植了Java ME游戏API到Android当中 第17章 Android...

    Google Android SDK开发范例大全(PDF高清完整版1)(4-1)

    第3章 用户人机界面 3.1 更改与显示文字标签——TextView标签的使用 3.2 更改手机窗口画面底色——drawable定义颜色常数的方法 3.3 更改TextView文字颜色——引用Drawable颜色常数及背景色 3.4 置换TextView文字——...

    Google Android SDK开发范例大全(PDF完整版4)(4-4)

    第3章 用户人机界面 3.1 更改与显示文字标签——TextView标签的使用 3.2 更改手机窗口画面底色——drawable定义颜色常数的方法 3.3 更改TextView文字颜色——引用Drawable颜色常数及背景色 3.4 置换TextView文字——...

    android的sqlite数据库查看器——sqlitespy1.9

    sqlitespy是一个快速和紧凑的GUI数据库管理员为sqlite 。它的内容sqlite3文件并执行的SQL对付他们。它的图形用户界面使得它很容易探讨,分析和操纵sqlite3数据库。

    android开发入门与实战(下)

    第3章 清点可用资本——AndroidSDK介绍 3.1 AndroidSDK基础 3.2 深入探寻AndroidSDK的密码 3.2.1 AndroidSDK目录结构 3.2.2 android.jar及内部结构 3.2.3 SDK文档及阅读技巧 3.2.4 先来热热身——AndroidSDK例子解析...

    《Google Android开发入门与实战》.pdf

    第5章 千里之行 始于足下——第一个应用helloworld 52 5.1 helloworld应用分析 52 5.1.1 新建一个android工程 52 5.1.2 填写工程的信息 52 5.1.3 编程实现 53 5.1.4 运行项目 54 5.2 调试项目 ...

    Android程序设计基础

     第二部分讨论Android的用户界面、二维图形、多媒体组件以及简单的数据访问。这些特性在大多数程序中都用得到。  第三部分深入探讨Android平台。这一部分介绍外部通信、基于位置的服务、内置SQLite数据库和三维...

    android开发入门与实战(上)

    第3章 清点可用资本——AndroidSDK介绍 3.1 AndroidSDK基础 3.2 深入探寻AndroidSDK的密码 3.2.1 AndroidSDK目录结构 3.2.2 android.jar及内部结构 3.2.3 SDK文档及阅读技巧 3.2.4 先来热热身——AndroidSDK例子解析...

    Google Android SDK开发范例大全的目录

    第3章 用户人机界面 3.1 更改与显示文字标签——TextView标签的使用 3.2 更改手机窗口画面底色——drawable定义颜色常数的方法 3.3 更改TextView文字颜色——引用Drawable颜色常数及背景色 3.4 置换TextView文字——...

    Google Android SDK开发范例大全(完整版附部分源码).pdf

    第3章 用户人机界面 3.1 更改与显示文字标签——TextView标签的使用 3.2 更改手机窗口画面底色——drawable定义颜色常数的方法 3.3 更改TextView文字颜色——引用Drawable颜色常数及背景色 3.4 置换TextView文字...

Global site tag (gtag.js) - Google Analytics