Beginning Android   译:Android起

1.     Using XML-Based Layouts    译:使用XML进行布局

While it is technically possible to create and attach widgets to our activity purely through Java code, the way we did in Chapter 4, the more common approach is to use an XML-based layout file. Dynamic instantiation of widgets is reserved for more complicated scenarios, where the widgets are not known at compile-time (e g., populating a column of radio buttons based on data retrieved off the Internet).

译:虽然纯粹通过Java代码在activity上创建和添加部件,在技术上是可行的,我们在第4章中做的一样,更常见的方法是使用一种基于XML的布局文件。动态的小部件实例保留更多,情况复杂,小工具在编译时不为人所知。例如,在数据检索了互联网基础上将单选按钮填充柱。

With that in mind, it’s time to break out the XML and learn how to lay out Android activities that way.

译:考虑到这一点,现在是时候来学习如何用此种方式来布置Android activities。

1.1What Is an XML-Based Layout?    译:什么是基于XML的布局

As the name suggests, an XML-based layoutis a specification of widgets’ relationships to each other—and to their containers (more on this in Chapter 7)—encoded in XML format. Specifically,Android considers XML-based layouts to be resources, and as such layout filesare stored in the res/layout directory inside your Android project.

译:正如其名称所示,一个基于XML的布局是一个关系到每个规格的小部件,和他们的容器(更多关于此内容的在第7章)编码的XML格式。具体来说,Android认为基于XML的布局是资源,因此布局文件存储在res /在你的Android项目布局目录中。

Each XML file contains a tree of elements specifying a layout of widgets and their containers that make up one view hierarchy. The attributes of the XML elements are properties, describing how awidget should look or how a container should behave. For example, if a Button element has an attribute value of android:textStyle  = "bold", that means that the text appearing on the face of the button should be rendered in a bold face fontstyle.

译:每个XML文件包含一个指定的部件和容器布局元素树,一种意见认为构成层次。对XML元素的属性,描述一个部件应如何看或者一个容器应如何运转。例如,如果一个按钮元素有一个Android的属性值:文字样式=“bold”,这意味着该文本出现在按钮的表面应该是呈现一个粗体字体样式.

Android’s SDK ships with a tool (aapt) which uses the layouts. This tool should be automatically invoked by your Android tool chain (e.g., Eclipse, Ant’s build.xml). Of particular importance to you as a developer is that aapt generates the R.java source file within your project, allowing you to access layouts and widgets within those layouts directly from your Java code.

译:Android的SDK中附带一个使用的布局的工具(aapt)。这个工具应自动调用你的Android工具链(例如,Eclipse中,Ant’s build.xml)。作为一个开发人员,尤其重要的是,在您的项目中aapt生成R.java源文件,让您能在那些布局中直接从Java代码中获取布局和部件。

1.2Why Use XML-Based Layouts?            译: 为什么基于XML的布局

Most everything you do using XML layout files can be achieved through Java code. For example, you could use set Typeface() to have a button render its text in bold, instead of using aproperty in an XML layout. Since XML layouts are yet another file for you to keep track of, we need good reasons for using such files.

译:使用XML布局文件做的大部分都可以通过Java代码。例如,你可以使用set Typeface()命令一个按钮使用粗体文本,而不是在一个XML布局中使用属性。由于XML布局是为你跟踪的另一个文件,所以我们需要好的理由来使用这样的文件。

Perhaps the biggest reason is to assist inthe creation of tools for view definition, such as a GUI builder in an IDE likeEclipse or a dedicated Android GUI designer like DroidDraw1. Such GUI builderscould, in principle, generate Java code instead of XML. The challenge isre-reading the UI definition to support edits—that is far simpler if the datais in a structured format like XML than in a programming language. Moreover,keeping generated XML definitions separated from hand-written Java code makes it less likely that somebody’s custom-crafted source will get clobbered by accident when the generated bits get re-generated. XML forms a nice middle ground between something that is easy for tool-writers to use and easy for programmers to work with by hand as needed.

译:也许最大的原因是为了在视图定义中协助工具的建立,如IDE中一个GUI创建者像Eclipse或者一个像DroidDraw1设计GUI图形用户界面建设者。这样GUI建设者们,在原则上,生成Java代码而不是XML。目前的挑战是重新阅读用户界面的定义,以支持编辑,也就是说,如果是像XLM的结构公式数据比一个程序语言中的数据简单的多。此外,保持生成的XML定义从手写的Java代码中分离,使得某人定制的来源意外重新生成不太可能。XML形成一个良好的中间立场,使工具作家使用更简便,程序员需要时手工工作更简易。

Also, XML as a GUI definition format is becoming more commonplace. Microsoft’s XAML2, Adobe’s Flex3, and Mozilla’s XUL4 all take a similar approach to that of Android: put layout details in an XMLfile and put programming smarts in source files (e.g., JavaScript for XUL).Many less-well-known GUI frameworks, such as ZK5, also use XML for view definition. While “following the herd” is not necessarily the best policy, it does have the advantage of helping to ease the transition into Android from anyother XML-centered view description language.

译:此外,XML作为一个GUI定义格式是越来越普遍。微软的XAML,Adobe的Flex,和Mozilla的XUL都采取Android类似的方法:把布局细节放在一个XML文件和把编程智慧资料放在源文件(例如,XUL中的JavaScript)。许多不太知名的图形用户界面框架,如ZK,还使用视图定义的XML。而“随大流”并不一定是最好的政策,但他们有优势帮助从任何其他XML为中心的观点描述语言轻松进入Android。

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

<Buttonxmlns:android="http://schemas.android.com/apk/res/android"

android:id="@+id/button"

android:text=""

android:layout_width="fill_parent"

android:layout_height="fill_parent"/>

The class name of the widget—Button—forms the name of the XML element. Since Button is an Android-supplied widget, we can just use the bare class name. If you create your own widgets as sub classes of android.view.View, you would need to provide a full package declaration as well.

译:部件,按钮的类名称形成XML元素的名称。因为按钮是Android提供的部件,我们可以只使用裸类的名称。如果您创建自己的部件作为android.view.View子小部件,您也将需要提供一个完整的包声明(如com.commonsware.android.MyWidget)。

Because we want to reference this button from our Java code, we need to give it an identifier  via the android:id attribute. We will cover this concept in greater detail later in this chapter.

译:因为我们要引用这个来自Java代码的按钮,我们需要通过android给它一个标识符:id属性。我们将在本章后面更详细的介绍这个概念。

The remaining attributes are properties of this Button instance:

译:其余的属性是此按钮实例属性:

•  android: text indicates the initial text to be displayed on the button face  ( in this case, an empty string)

译:android:文字表示的初始文本将显示在按钮(这种情况显示空字符串)

• android:layout_width and android : layout_height tell Android to have the button’s

译:android:layout_width和Android:layout_height命令android有按钮的

width and height fill the “parent”, in this case the entire screen—these attributes will be covered in greater detail in Chapter 7.

译:宽度和高度填写 “parent”,这种情况下,整个屏幕。将这些属性将在第7章中详解。

Since this single widget is the only content in our activity, we only need this single element. Complex UIs will require a whole tree of elements, representing the widgets and containers that control their positioning. All the remaining chapters of this book will use the XML layout form whenever practical, so there are dozens of other examples of more complex layouts for you to peruse from Chapter 7 onward.

译:由于这个单一部件是activity的仅有内容,我们只需要这一个因素。复杂的用户界面将需要整个树的元素,代表工具和容器,控制自己的定位。所有的这本书余下的章节将使用XML布局,所以还有数十种更复杂的其他布局实例,请前进到第七章仔细阅读。

1.3 What’s with the @ Signs?         译:@符号有什么用途?

Many widgets and containers only need to appear in the XML layout file and do not need to be referenced in your Java code. For example, a static label (TextView) frequently only needs to be in the layout file to indicate where it should appear. These sorts of elements in the XML file do not need to have the android:id attribute to give them a name.

译:  许多部件和容器只需要出现在XML布局文件,不须引用在Java代码。例如,一个静态标签(TextView)只需要在布局文件中以表明它应该出现在那里。在XML文件中各种元素文件不需要有android:id属性给他们一个名称。

Anything you do want to use in your Javasource, though, needs an android:id.

译:任何你想要在Java资源中使用的东西,都需要一个android:id 。

The convention is to use @+id/... as the idvalue, where the ... represents your locally unique name for the widget in question. In the XML layout example in the preceding section, @+id/ button is the identifier for the Button widget.

译:该公约是使用@ +id...作为ID值,其中的...代表你locally unique名称有问题的部件。在上一节的XML布局的例子中,@ +id是按钮控件的标识符。

Android provides a few special android:id values, of the form @android:id/.... We will see some of these in various chapters of this book, such as Chapters 8 and 10.

译:android提供了一些特殊的android:ID值,形式@android:id/...我们将在这本书的不同章节中看到这些,例如第八章和第十章。

We Attach These to the Java How?

译:我们将这些附加到Java…如何?

Given that you have pains takingly set up the widgets and containers in an XML layout file named main.xml stored in res/layout, all you need is one statement in your activity’s onCreate() call back to use that layout:

译:既然你有意建立一个XML配置文件的工具和容器,名为main.xml存储res/layout,所有你需要的是一个在您activity的OnCreate()回调以使用该版式:

This is the same setContentView() we used earlier, passing it an instance of a View subclass (in that case, a Button).The Android-built view, constructed from our layout, is accessed from that code-generated R class. All of the layouts are accessible under R.layout, keyed by the base name of the layout file—main.xml results in R.layout.main.

译:这是相同的setContentView(),我们前面使用,通过它的一个视图子类的实例(在这种情况下,一个按钮)。该android制造的观点,来自我们的布局,是从访问该代码生成的R类。所有的布局都可以访问R.layout,由基地键控布局文件的名称- main.xml result inR.layout.main.

To access our identified widgets, use findViewById(), passing in the numeric identifier of the widget in question.That numeric identifier was generated by Android in the R class asR.id.something (where something is the specific widget you are seeking). Those widgets are simply subclasses of View, just like the Button instance we createdin Chapter 4.

译:要访问确定部件,使用findViewById(),在数字标识符传递有问题的部件。这一数字标识符生成的R类由android在R.id.something(其中一些是你正在寻找的具体部件)。这些部件是只是子类的视图,就像我们在第四章中创建Button实例。

The Rest of the Story In the original Now demo, the button’s face would show the current time, which would reflect when the button was last pushed (or when the activity was first shown, if the button had not yet been pushed). Most of that logic still works, even in this reviseddemo (NowRedux). However, rather than instantiating the Button in our activity’s onCreate() callback, we can reference the one from the XML layout:

译:剩下的部分在原始的Now演示中,按钮的表面便会显示当前的时间,这将反映当按钮被最后按下时显示的时间(或者如果在按钮尚未被按下时显示)。这种逻辑仍然适用,即使在该修订演示(NowRedux)中。尽管如此,在activity’s onCreate() callback中的实例,我们可以从XML的布局参考一个例子:

packagecom.commonsware.android.layouts;

import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import android.widget.Button; importjava.util.Date;

public class NowRedux extendsActivity implements View.OnClickListener { Button btn;

@Override

public void onCreate(Bundleicicle)  { super.onCreate(icicle);

setContentView(R.layout.main);

btn=(Button)findViewById(R.id.button);btn.setOnClickListener(this);updateTime();

}

public void onClick(View view)  { updateTime();

}

private void updateTime()  {

btn.setText(new Date().toString());}

}

The first difference is that rather than setting the content view to be a view we created in Java code, we set it to reference the XML layout (set ContentView(R.layout.main)). The R.java source file will be updated when we rebuild this project to include a reference to our layout file (stored as main.xml in our project’s res/layout directory).

译:第一个区别是,在Java代码中设置内容视图作为视图,我们将它设置为引用的XML布局(set ContentView(R.layout.main))。该R.java源文件将被更新,当我们重建这个项目,包括对我们布局参考文件(存储在main.xmlin our project’s res/layoutdirectory )。

The other difference is that we need to getour hands on our Button instance, for which we use the findViewById() call.Since we identified our button as @+id/button, we can reference the button’sidentifier as R.id.button. Now, with the Button instance in hand, we can set the call back and set the label as needed.

译:另一个不同是,我们需要亲手实验按钮实例,我们使用findViewById()调用。既然我们发现按钮为@ +id/button,我们可以参考按钮的标识符R.id.button。现在,随着手手头上的实例,我们可以设置回调并根据需要设置标签。

2.    Employing Basic Widgets         译:使用基本组件

Every GUI toolkit has some basic widgets:fields, labels, buttons, etc. Android’s toolkit is no different in scope, and the basic widgets will provide a good introduction as to how widgets work inAndroid activities.

译:  每一个GUI工具包都有一些基本的部件:字段,标签,按钮等,Android的工具包在范围内没有不同,其基本部件将提供一个良好的介绍,关于这些部件在Android activities中是如何运行的。

The simplest widget is the label, referredto in Android as a TextView. Like in most GUI toolkits, labels are bits of text not editable directly by users. Typically, they are used to identify adjacent widgets (e.g., a “Name:” label before a field where one fills in a name).

译: 指派标签是最简单的部件是标签,在Android提到的作为一个TextView。像大多数的GUI工具包,标签的文本是不可被用户直接编辑的。通常情况下,它们被用来确定相邻部件(例如,一个“姓名:”一个填充姓名前的标签)。

In Java, you can create a label by creatinga TextView instance. More commonly, though, you will create labels in XML layout files by adding a TextView element to the layout, with an android:text property to set the value of the label itself. If you need to swap labels based on certain criteria, such as internationalization, you may wish to use a resource reference in the XML instead, as will be described in Chapter 9. TextView hasnumerous other properties of relevance for labels, For example, in the Basic/Label project, you will find the following layout file:

译:在Java中,你可以通过创建一个TextView的实例l来创建一个标签。更常见的,虽然,你将通过添加一个TextView元素到布局来在XML布局文件中创建标签,与一个Android:文本属性来设置标签的本身价值。如果您需要交换基于某些标准的标签,例如国际化,你可能想使用XML中的资源参考代替,这些将在第9章叙述。例如,在Basic/Label项目中,你将找到下列布局文件:

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

<TextViewxmlns:android=http://schemas.android.com/apk/res/android

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="You were expectingsomething profound?" />

2.1 Button,Who’s Got the Button?        译:  按钮,归属于谁?

We’ve already seen the use of the Button widget in Chapters 4 and 5. As it turns out, Button is a subclass of TextView,so everything discussed in the preceding section in terms of formatting the face of the button still holds.

译:  我们已经在第4和第5章看到了按钮部件用法。按钮是文本视图的一个子类,所以一切都在上一节讨论了,按钮格式所面临的问题仍然成立。

Android has two widgets to help you embed images in your activities: ImageView and ImageButton. As the names suggest,they are image-based analogues to TextView and Button, respectively. Each widget takes an android:src attribute (in an XML layout) to specify what picture to use. These usually reference a drawable resource, described in greater detail in the chapter on resources. You can also set the image contentbased on a Uri from a content provider via setImageURI().

译:Android有两个部件,来帮助你将照片嵌入activities:ImageView和ImageButton。正如名称所暗示的,他们是分别对于文本视图和按钮基于图像的类似物。每个部件带有一个android:src属性(在一个XML布局中),指明使用什么图片。这些通常引用一个可绘制的资源,在讲资源的这个章节中更详细地描述了。您还可以通过setImageURI()从内容提供商在Uri基础上设置图像。

ImageButton, a subclass of ImageView, mixesin the standard Button behaviors, for responding to clicks and what not.

译:ImageButton控件,一个ImageView子类,混合在标准按钮行为中,应对点击和诸如此类的东西。

For example, take a peek at the main.xmllayout from the Basic/ImageView sample project:

译:例如,从Basic/ImageView样本项目中看main.xml布局,这可以在http://apress.com以及所有其他代码示例种找到。

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

<ImageViewxmlns:android=http://schemas.android.com/apk/res/android

android:id="@+id/icon"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:adjustViewBounds="true"

android:src="@drawable/molecule"/>

2.2 Fields ofGreen. Or Other Colors.    译:  绿色字段或者其他色彩

Along with buttons and labels, fields arethe third “anchor” of most GUI toolkits. In Android, they are implemented via the EditText widget, which is a subclass of the TextView used for labels.

译:紧接着按钮和标签,字段是大多数GUI工具包的第三个“锚”。在Android中,他们通过EditText部件运行,它是标签的一个子类TextView。

Along with the standard TextView properties(e.g., android:textStyle), EditText has many others that will be useful for you in constructing fields, including: Beyond those, you can configure fields to use specialized input methods, such as android:numeric for numeric-only input,android:password for shrouded password input, and android:phoneNumber for entering in phone numbers. If you want to create your own input method scheme(e.g., postal codes, Social Security numbers), you need to create your own implementation of the InputMethod interface, then configure the field to use it via android: inputMethod. For example, from the Basic/Field project, here is anXML layout file showing an EditText:

译:  随着标准TextView属性(例如,Android:文本样式),EditText有许多其他方面可以帮助你创建字段,包括:除了这些,你可以使用专门配置字段输入方法,如android:仅数字输入numeric,android:为笼罩密码输入密码,还有Android:phoneNumber进入电话号码。如果你想创建自己的输入法计划(如邮政编码,社会安全号码),您需要创建自己的执行情况InputMethod接口,然后通过android设定字段来使用:inputMethod。例如,从the Basic/Field项目,这里是一个XML布局文件显示EditText:

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

<EditText

xmlns:android=http://schemas.android.com/apk/res/androidandroid:id="@+id/field"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:singleLine="false"/>

Note that android:singleLine is false, sousers will be able to enter in several lines of text. For this project, theFieldDemo.java file populates the input field with some prose:

译:请注意android:singleLine是错误的,因此,用户将能够输入几行文字。对于这一项目,FieldDemo.java文件填充了一些散文输入栏:

packagecom.commonsware.android.basic;

import android.app.Activity;

import android.os.Bundle;

import android.widget.EditText;

public class FieldDemo extendsActivity  { @Override

public void onCreate(Bundleicicle)  { super.onCreate(icicle);

setContentView(R.layout.main);

EditText fld=(EditText)findViewById(R.id.field);

fld.setText("Licensed under theApache License, Version  2.0 " +"(the  \"License\"); youmay not use this file " + "except in compliance with the License. Youmay "  + "obtain a copy of theLicense at " +

"http://www.apache.org/licenses/LICENSE-2.0");}

}

Note Android’s emulator only allows one application in the launcher per unique Java package. Since all the demos in this chapter share the com.commonsware.android.basic package, you will only see one of these demos in your emulator’s launcher at any one time.

译:  注意:Android的模拟器只允许在每一个独特的Java包发射器中应发射用。由于本章中的所有演示共享com.commonsware.android.basic包,您将只能在你的模拟器发射的任何时候的看到这些演示之一。

Another flavor of field is one that offers auto-completion, to help users supply a value without typing in the whole text.That is provided in Android as the AutoCompleteTextView widget and is discussedin Chapter 8.

译:另一个字段的特色,提供自动完成,以帮助用户在整个无文本输入一个值。这是作为AutoCompleteTextView部件在Android中提供的并将在第8章讨论。

Beginning Android相关推荐

  1. android sex games app,Beginning Android Games 2nd Edition

    摘要: Beginning Android Games, Second Edition offers everything you need to join the ranks of successf ...

  2. android games 1,Beginning Android Games

    Beginning Android Games 编辑 锁定 讨论 上传视频 <Beginning Android Games>是2011年Apress出版的图书,作者是Mario Zech ...

  3. Using Preferences(Beginning Android)

    To get access to the preferences, you have three APIs to choose from: • getPreferences() from within ...

  4. Beginning Android Framework --Phone AndroidManifest.xml

    本篇笔记将从AndroidManifest.xml文件着手来分析Contacts模块. 首 先,AndroidManifest.xml文件授予了Contacts程序某些权限,包括 CALL_PRIVI ...

  5. 12本最优秀的Android开发电子书强力推荐

    如今已经是手机互联网时代,手机应用越来越普及.Android作为基本的手机操作系统.吸引了众多开发人员開始为Android系统开发应用. 假设你正在开发或者准备进行Android的开发,我们今天推荐的 ...

  6. Android学习笔记(七):多个Activity和Intent

    根据www.mars-droid.com:Andriod开发视频教学,先跳过书本<Beginning Android 2>的几个章,我是这两个资源一起看,需要进行一下同步.先初步了解一下应 ...

  7. 【073】Android 数据存储(SQLite)

    目录: I. 使用 SharedPreferences 来存储应用程序的数据 II. 将应用程序的数据存储到内部存储器中 III. 将应用程序的数据存储到外部存储器中 IV. 通过 SQLite 数据 ...

  8. Android游戏开发教程汇总

    Android游戏开发教程汇总 把最近搜集到的Android游戏开发教程列出来,希望对大家有用. 1.Android2.0游戏开发实战宝典源代码,当然可能大家已经把书也买回家啦. 2.Pro.Andr ...

  9. Android Platform 3.0 SDK和Eclipse ADT安装记录三

    有用的链接(有些需要Android NDK) 一.游戏库.开发库 1. ONScripter on Anroid のページ http://onscripter.sourceforge.jp/andro ...

最新文章

  1. 【java】实现数据在页面之间传输
  2. DeepFaceLab 换脸
  3. IE中a标签绝对定位时才生的bug
  4. 如何解决 SQL Server 安装程序中的 COM+ 系统配置检查失败问题
  5. 优秀程序员和一般程序员差别在哪?
  6. ASP.NET网站发布-允许更新此预编译站点
  7. 小甲鱼python课后题简书_【Python爬虫】-笨办法学 Python 习题01-10
  8. C++之继承探究(十):抽象基类与纯虚函数
  9. Dell 12G服务器 手动安装RedHat 6.X
  10. Maven 项目关于 plexus-utils:jar的错误解决
  11. cron 任务执行表达式
  12. linux pro*c环境配置,Pro*C 环境配置(RedHat +Oracle 10g)
  13. 卡特兰数(JAVA大数)Buy the Ticket
  14. WebView---Android与Javascript交互之入门
  15. 无锡工艺技术计算机信息管理论文,无锡工艺职业技术学院05/06学年第一学期.doc...
  16. androrid按键事件
  17. RxJava 学习笔记(七) --- Filtering 过滤操作
  18. 2017年大数据可视化机遇,这5大行业不容错过
  19. c语言(15 5)是多少,试题五(共 15分) 阅读以下关于 C语言及 C代码的叙述,回答问题 1至..._考试资料网...
  20. STM32学习5——舵机控制

热门文章

  1. 腾讯视频如何设置热键
  2. Qt Quick 之 PathView 详解
  3. python os.sep 使用
  4. Android小Demo——通过MQTT协议连接OneNet平台(旧版)
  5. 知识付费的时代,哪些应该付费学习?
  6. 关于ECMA、ECMAScript、TC39、ES、Stage等概念的科普
  7. 硬盘无法访问由于IO设备错误,无法运行此项请求,里面的资料怎么寻回
  8. ONEPTP 挂机冲流量 网赚 稳定入帐项目!
  9. java计算机毕业设计智能推荐二手车交易网站源码+mysql数据库+系统+部署+lw文档
  10. java containsany_Java contains用法示例