您的位置:首页 > 其它

安卓实训教程第一天:搭建环境,并且运行第一个helloworld以及电话拨号器

2014-05-19 20:30 579 查看
1、首先进行SDK的安装和下载,我们这次使用的是安卓4.4.2版本。

2、创建第一个安卓模拟器,配置好相关属性,页面大小,内存等等,然后耐心的等待设备的启动吧。

3、创建第一个安卓工程——lesson01。时间也比较长。

4、在HelloWorldActivity.java文件中创建textView来显示第一个文件HelloWorld。。。并在activity_hello_world.xml中通过拉扯按钮来完成对初步的线性布局。然后将工程文件运行到模拟器上,成功显示helloworld.

5、创建一个phone的J***A文件,然后出现相应的activity_phone.xml,通过简单的拖扯控件,或者自己手动创建控件,来完成对拨号器软件的初步布局。要注意的是在string中生命id 名字还有内容,对应的XML文件中。然后部署到虚拟机上。然后测试,成功。

翻译部分:


Creating an Android Project

An Android project contains all the files that comprise the source code for your Android app. The Android SDK tools make it easy to start a new Android project with a set of default project directories and files.This lesson shows how to create a new project
either using Eclipse (with the ADT plugin) or using the SDK tools from a command line.


创建一个Android工程


一个Android项目包含了所有包括用于你的Andr​​oid的应用程序的源代码文件。Android SDK中的工具可以很容易地开始了一套默认的项目目录和文件的新的Andr​​oid项目。本课程说明如何要么使用Eclipse(与ADT插件),或使用从一个命令行的SDK工具来创建一个新的项目。


Running Your App

If you followed the previous
lesson to create an Android project, it includes a default set of "Hello World" source files that allow you to immediately run the app.

How you run your app depends on two things: whether you have a real Android-powered device and whether you're using Eclipse. This lesson shows you how to install and run your app on a real device and on the Android emulator, and in both cases with either Eclipse
or the command line tools.

Before you run your app, you should be aware of a few directories and files in the Android project:


运行你的应用程序

如果你是按照上一课创建一个Android项目,它包含了“Hello
World”的源文件,让您可以立即运行该应用程序的缺省设置。

您如何运行你的应用程序依赖于两件事情:你是否有一个真正的Andr​​oid设备,并不管你是使用Eclipse。本课程将告诉您如何安装和真实设备,并在Android模拟器上运行你的应用程序,并在两种情况下使用Eclipse或命令行工具。

在你运行你的应用程序,你应该知道,在Android项目的几个目录和文件:

AndroidManifest.xml
The manifest
file describes the fundamental characteristics of the app and defines each of its components. You'll learn about various declarations in this file as you read more training classes.
One of the most important elements your manifest should include is the
<uses-sdk>
element.
This declares your app's compatibility with different Android versions using the
android:minSdkVersion
and
android:targetSdkVersion
attributes.
For your first app, it should look like this:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" ... >
    <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" />
    ...
</manifest>

You should always set the
android:targetSdkVersion
as
high as possible and test your app on the corresponding platform version. For more information, read Supporting
Different Platform Versions.
src/
Directory for your app's main source files. By default, it includes an
Activity
class
that runs when your app is launched using the app icon.
res/
Contains several sub-directories for app
resources. Here are just a few:
drawable-hdpi/
Directory for drawable objects (such as bitmaps) that are designed for high-density (hdpi) screens. Other drawable directories contain assets designed for other screen densities.
layout/
Directory for files that define your app's user interface.
values/
Directory for other various XML files that contain a collection of resources, such as string and color definitions.

When you build and run the default Android app, the default
Activity
class
starts and loads a layout file that says "Hello World." The result is nothing exciting, but it's important that you understand how to run your app before you start developing.

AndroidManifest.xml文件
清单文件描述了应用程序的基本特性,并定义它的每一个组成部分。您将了解在这个文件中各项声明,当你阅读更多培训课程。
其中最重要的内容资讯清单应包括的是
<uses-sdk>
元素。此声明与使用不同版本的Android您的应用程序的兼容性
的android:minSdkVersion
Android版
 ​​本:targetSdkVersion
属性。为了您的第一个应用程序,它看起来应该像这样:
<manifest  xmlns:android = "http://schemas.android.com/apk/res/android" ... > 
    <uses-sdk  android:minSdkVersion = "8"  android:targetSdkVersion = "17"  /> 
    ... 
</manifest>

你应该总是设置
的android:targetSdkVersion
尽可能高,并在相应的平台版本测试您的应用程序。欲了解更多信息,请阅读支持不同的平台版本
SRC /
目录为你的应用程序的主源文件。默认情况下,它包含一个
活动
运行时,您的应用程序使用的应用程序图标启动类。
业绩/
包含几个子目录的应用程序资源。这里仅仅是几个例子:
绘制-HDPI /
目录可绘制对象(如位图)是专为高密度(HDPI)屏幕。其他可绘制目录包含专为其他屏幕密度的资产。
布局/
目录定义您的应用程序的用户界面文件。
值/
目录中包含资源的集合等各种XML文件,比如字符串和颜色的定义。

当你建立并运行默认的Android应用程序,默认
活动
类启动并加载一个布局文件,上面写着的“Hello
World”。其结果是平平淡淡,但您了解如何运行你的程序,你开始开发之前,这一点很重要。


Building a Simple User Interface

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 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应用程序的图形用户界面使用的层次结构建立
视图
视图组
对象。
查看
对象通常是UI小部件,如按钮文本字段
视图组
对象是不可见的视图的容器定义如何的子视图的布局,如在网格或垂直列表。

Android提供了对应的子类的XML词汇表
视图
视图组
,因此您可以在XML中使用的UI元素的层次结构中定义你的用户界面。


Create a Linear Layout

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

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.

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.

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:
<?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.

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

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


创建一个线性布局

打开
activity_main.xml
从文件
RES /布局/
目录下。

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

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

首先,删除
<TextView>
元素和改变
<RelativeLayout>
元素
<LinearLayout>
。然后添加
机器人:定位
属性并将其设置为
“横向”
。结果看起来像这样:
<?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
是一个视图组(子类
视图组
,规定了子视图在垂直或水平方向,所指定的)
机器人:定位
属性。一个为每个孩子
的LinearLayout
在其出现在XML中的顺序显示在屏幕上。

其他两个属性,
机器人:layout_width
机器人: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 specify the
EditText
object's
properties. Here’s how you should declare it inside the
<LinearLayout>
element:
<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 toProviding
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).
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
).
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'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 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.
android:layout_width
and
android: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 the
EditText
element
would fill the screen, because it would match the size of the parent
LinearLayout
.
For more information, see the Layouts guide.
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.

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 as
id
or
string
),
so using the same name does not cause collisions.


添加一个文本字段

要创建一个用户可编辑的文本字段,添加一个
<EditText>
里面的元素
<LinearLayout>


像每一个
视图
对象,你必须定义某些XML属性来指定
的EditText
对象的属性。下面是你应该在里面声明它
<LinearLayout>
元素:
<EditText  android:id = "@+id/edit_message" 
        android:layout_width = "wrap_content" 
        android:layout_height = "wrap_content" 
        android:hint = "@string/edit_message"  />



关于资源对象

一个资源对象很简单,就是与一个应用程序的资源,如位图,布局文件或字符串相关的唯一整数名称。
每个资源都在你的项目的定义相应的资源对象
根/ R.java文件
的文件。您可以使用对象名称在
[R
类来引用你的资源,例如当您需要为指定字符串值
的android:提示
属性。你还可以创建你的视图使用任意的关联资源ID
的android:ID
属性,它允许你引用的其他代码视图。
SDK工具生成
R.java文件
每次编译您的应用程序的时间。你不应该手动修改这个文件。
欲了解更多信息,请阅读指南,提供了资源

关于这些属性:

机器人:ID
这提供了一个独特的标识符视图,您可以用它来从你的应用程序代码,如阅读和操作对象引用的对象(你会看到这个在下一课)。
at符号(
@
),当你指的是从XML的任何资源对象是必需的。它后面的资源类型(
ID
在这种情况下),斜线,则该资源名称(
edit_message
)。
加号(
+
资源类型之前)是必要的,只有当你定义一个资源ID的第一次。当你编译的应用程序,SDK工具使用ID名称在项目中创建一个新的资源ID
根/
 R.java文件
是指文件
的EditText
元素。一旦资源ID被宣告一次通过这种方式,其他参考文献的编号并不需要的加号。指定一个新的资源ID,而不是需要具体的资源,如字符串或布局仅当使用加号是必要的。见sidebox的有关资源对象的详细信息。
机器人:layout_width
机器人:layout_height
除了 ​​使用特定大小的宽度和高度,在
“wrap_content”
值指定为需要调整视图内容的视图应该只为大。如果你要改用
“match_parent”
,那么
的EditText
元素将填满整个屏幕,因为它会匹配父的大小
的LinearLayout
。欲了解更多信息,请参阅布局指南。
机器人:提示
这是一个默认的字符串显示在文本字段为空。而不是使用硬编码字符串作为值时,
“@字符串/ edit_message”
值指的是在一个单独的文件中定义的字符串资源。因为这是指一种具体的资源(不只是一个标识符),它不需要加号。但是,因为你还没有定义的字符串资源,但你会看到在第一次编译器错误。您将通过定义字符串解决这个问题在下一节。

注:此字符串资源具有相同的名称作为元素的ID:
edit_message
。但是,引用资源由资源类型(如始终范围
ID
字符串
),所以使用相同的名称不会引起冲突。


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.

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

While you’re in this file, also add a "Send" string for the button you’ll soon add, called
"button_send"
.

The result for
strings.xml
looks like this:
<?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="action_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.


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.



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

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.

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.
<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
        android:layout_weight="1"
        android:layout_width="0dp"
        ... />


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



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

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:

In Eclipse, click Run

from
the toolbar.
Or from a command line, change directories to the root of your Android project and execute:
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.


添加字符串资源

当你需要在用户界面中添加文字,您应该总是指定每个字符串作为资源。字符串资源,让您可以管理在一个位置,这使得它更容易找到并更新文本的所有UI文本。外部化的字符串还允许您通过提供替代定义为每个字符串资源本地化您的应用程序,以不同的语言。

默认情况下,你的Android项目包括在一个字符串资源文件
RES /价值观/ strings.xml中
。添加一个名为新的字符串
“edit_message”
并将其值设置为“输入信息”。(您可以删除“的hello_world”的字符串。)

当你在这个文件中,还添加了“发送”字符串键,你很快就会增加,被称为
“button_send”


其结果为
strings.xml中
看起来像这样:
<?XML版本= “1.0” 编码= “UTF-8” ?> 
<resources> 
    <字符串 名称= “APP_NAME” > 我的第一个应用程序</字符串> 
    <字符串 名称= “edit_message” > 输入message </string> 
    <string  name = "button_send" > Send </string> 
    <string  name = "action_settings" > Settings </string> 
    <string  name = "title_activity_main" > MainActivity </string> 
</resources>


如需使用字符串资源本地化您的应用程序的其他语言的详细信息,请参阅支持不同的设备 类。


添加一个按钮

现在添加
的<button>
到布局,紧随以下
<EditText>
元素:
<Button 
        android:layout_width = "wrap_content" 
        android:layout_height = "wrap_content" 
        android:text = "@string/button_send"  />


的高度和宽度都设置为
“wrap_content”
这样的按钮仅大如必要的,以适应该按钮的文本。此按钮不需要
机器人:ID
属性,因为它不会从活动代码引用。


使输入框填写的屏幕宽度

布局是目前设计成使得两个
的EditText
按钮
部件是只有大如必要以适合其内容,如图2。



图2的
的EditText
按钮
部件都有各自的宽度设置为
“wrap_content”


这工作得很好了按钮,但没有得到很好的文本字段,因为用户可能会输入一些较长。所以,这将是很好的填补未使用的屏幕的宽度与文本字段。你可以在里面一个做到这一点
的LinearLayout
的重量属性,您可以指定使用
的android:layout_weight
属性。

权重值是一个数字,指定的剩余空间,每个视图应该消耗的量,相对于由同级意见消耗量。这工作有点像成分的饮料配方量:“2份伏特加,1份咖啡力娇酒”是指三分之二的饮料是伏特加。例如,如果给一个视图的重量为2和1的另一个重量的总和是3,所以在第一视图中填充剩余空间的2/3和第二视图填充的其余部分。如果添加了第三个视图,并给它的权值为1,那么第一个视图(重量2)现在得到1/2的剩余空间,而每个剩下的两个获得1/4。

默认权重为所有视图为0,因此,如果您指定的任何权重值大于0到只有一个视图,则该视图填充后的所有意见都给予他们所需要的空间,无论空间仍然存在。因此,要填写你的布局的剩余空间用
的EditText
元素,给它的权值为1,离开按钮没有重量。
<的EditText 
        的android:layout_weight = “1” 
        ... />


为了提高布局的效率,当您指定的重量,你应该改变宽度
的EditText
为零(0DP)。宽度设置为零布局提高性能,因为使用
“wrap_content”
作为宽度要求系统计算的宽度是最终无关紧要的,因为权重值需要另一个宽度计算,以填补剩余空间。
<的EditText 
        的android:layout_weight = “1” 
        机器人:layout_width = “0DP” 
        ... />


图3显示了当你将所有的重量到结果
的EditText
元素。



图3的
的EditText
小部件提供的所有布局的重量,因此填补了剩余空间
的LinearLayout


这里是你的完整布局文件现在应该怎么看:
<?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>


这种布局是由默认应用
活动
,当你创建项目的SDK工具生成的类,所以你现在可以运行应用程序来查看结果:

在Eclipse中,单击运行

在工具栏中。
或者在命令行,将目录更改为你的Andr​​oid项目的根目录,然后执行:
蚂蚁调试
的adb安装斌/ MyFirstApp - 调试。apk文件


继续下一课来学习如何应对按下按钮,从文本字段读取内容,启动另一个活动,等等。


Starting Another Activity

PREVIOUSNEXT


THIS LESSON TEACHES YOU TO

Respond
to the Send Button
Build
an Intent
Start
the Second Activity
Create
the Second Activity
Receive
the Intent
Display
the Message


YOU SHOULD ALSO READ

Installing
the SDK

After completing the previous
lesson, you have an app that shows an activity (a single screen) with a text field and a button. In this lesson, you’ll add some code to
MainActivity
that starts a new activity when
the user clicks the Send button.


Respond to the Send Button

To respond to the button's on-click event, open the
activity_main.xml
layout file and add the
android:onClick
attribute
to the
<Button>
element:
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/button_send"
    android:onClick="sendMessage" />

The
android:onClick
attribute’s
value,
"sendMessage"
, is the name of a method in your activity that the system calls when the user clicks the button.
Open the
MainActivity
class (located in the project's
src/
directory)
and add the corresponding method:
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
    // Do something in response to button
}

This requires that you import the
View
class:
import android.view.View;


Tip: In Eclipse, press Ctrl + Shift + O to import missing classes (Cmd + Shift + O on Mac).
In order for the system to match this method to the method name given to
android:onClick
,
the signature must be exactly as shown. Specifically, the method must:

Be public
Have a void return value
Have a
View
as
the only parameter (this will be the
View
that
was clicked)

Next, you’ll fill in this method to read the contents of the text field and deliver that text to another activity.


Build an Intent

An
Intent
is
an object that provides runtime binding between separate components (such as two activities). The
Intent
represents
an app’s "intent to do something." You can use intents for a wide variety of tasks, but most often they’re used to start another activity.
Inside the
sendMessage()
method, create an
Intent
to
start an activity called
DisplayMessageActivity
:
Intent intent = new Intent(this, DisplayMessageActivity.class);

The constructor used here takes two parameters:

A
Context
as
its first parameter (
this
is used because the
Activity
class
is a subclass of
Context
)
The
Class
of
the app component to which the system should deliver the
Intent
(in
this case, the activity that should be started)


Sending an intent to other apps

The intent created in this lesson is what's considered an explicit intent, because the
Intent
specifies
the exact app component to which the intent should be given. However, intents can also be implicit, in which case the
Intent
does
not specify the desired component, but allows any app installed on the device to respond to the intent as long as it satisfies the meta-data specifications for the action that's specified in various
Intent
parameters.
For more information, see the class about Interacting
with Other Apps.

Note: The reference to
DisplayMessageActivity
will raise an error if you’re using an IDE such as Eclipse because the class doesn’t exist yet. Ignore the error for now;
you’ll create the class soon.
An intent not only allows you to start another activity, but it can carry a bundle of data to the activity as well. Inside the
sendMessage()
method,
use
findViewById()
to
get the
EditText
element
and add its text value to the intent:
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);


Note: You now need import statements for
android.content.Intent
and
android.widget.EditText
.
You'll define the
EXTRA_MESSAGE
constant in a moment.
An
Intent
can
carry a collection of various data types as key-value pairs called extras. The
putExtra()
method
takes the key name in the first parameter and the value in the second parameter.
In order for the next activity to query the extra data, you should define the key for your intent's extra using a public constant. So add the
EXTRA_MESSAGE
definition
to the top of the
MainActivity
class:
public class MainActivity extends Activity {
    public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
    ...
}

It's generally a good practice to define keys for intent extras using your app's package name as a prefix. This ensures they are unique, in case your app interacts with other apps.


Start the Second Activity

To start an activity, call
startActivity()
and
pass it your
Intent
.
The system receives this call and starts an instance of the
Activity
specified
by the
Intent
.
With this new code, the complete
sendMessage()
method that's invoked by the Send button now looks like this:
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
    Intent intent = new Intent(this, DisplayMessageActivity.class);
    EditText editText = (EditText) findViewById(R.id.edit_message);
    String message = editText.getText().toString();
    intent.putExtra(EXTRA_MESSAGE, message);
    startActivity(intent);
}

Now you need to create the
DisplayMessageActivity
class in order for this to work.


Create the Second Activity



Figure 1. The new activity wizard in Eclipse.

To create a new activity using Eclipse:

Click New

in
the toolbar.
In the window that appears, open theAndroid folder and select Android Activity. Click Next.
Select BlankActivity and click Next.
Fill in the activity details:

Project: MyFirstApp
Activity Name: DisplayMessageActivity
Layout Name: activity_display_message
Title: My Message
Hierarchial Parent: com.example.myfirstapp.MainActivity
Navigation Type: None

Click Finish.

If you're using a different IDE or the command line tools, create a new file named
DisplayMessageActivity.java
in the project's
src/
directory,
next to the original
MainActivity.java
file.
Open the
DisplayMessageActivity.java
file. If you used Eclipse to create this activity:

The class already includes an implementation of the required
onCreate()
method.
There's also an implementation of the
onCreateOptionsMenu()
method,
but you won't need it for this app so you can remove it.
There's also an implementation of
onOptionsItemSelected()
which
handles the behavior for the action bar'sUp behavior. Keep this one the way it is.

Because the
ActionBar
APIs
are available only on
HONEYCOMB
(API
level 11) and higher, you must add a condition around the
getActionBar()
method
to check the current platform version. Additionally, you must add the
@SuppressLint("NewApi")
tag to the
onCreate()
method
to avoid lint errors.
The
DisplayMessageActivity
class should now look like this:
public class DisplayMessageActivity extends Activity {

    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_display_message);

        // Make sure we're running on Honeycomb or higher to use ActionBar APIs
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            // Show the Up button in the action bar.
            getActionBar().setDisplayHomeAsUpEnabled(true);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home:
            NavUtils.navigateUpFromSameTask(this);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

If you used an IDE other than Eclipse, update your
DisplayMessageActivity
class with the above code.
All subclasses of
Activity
must
implement the
onCreate()
method.
The system calls this when creating a new instance of the activity. This method is where you must define the activity layout with the
setContentView()
method
and is where you should perform initial setup for the activity components.

Note: If you are using an IDE other than Eclipse, your project does not contain the
activity_display_message
layout that's requested by
setContentView()
.
That's OK because you will update this method later and won't be using that layout.


Add the title string

If you used Eclipse, you can skip to the next
section, because the template provides the title string for the new activity.
If you're using an IDE other than Eclipse, add the new activity's title to the
strings.xml
file:
<resources>
    ...
    <string name="title_activity_display_message">My Message</string>
</resources>


Add it to the manifest

All activities must be declared in your manifest file,
AndroidManifest.xml
, using an
<activity>
element.
When you use the Eclipse tools to create the activity, it creates a default entry. If you're using a different IDE, you need to add the manifest entry yourself. It should look like this:
<application ... >
    ...
    <activity
        android:name="com.example.myfirstapp.DisplayMessageActivity"
        android:label="@string/title_activity_display_message"
        android:parentActivityName="com.example.myfirstapp.MainActivity" >
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.example.myfirstapp.MainActivity" />
    </activity>
</application>

The
android:parentActivityName
attribute
declares the name of this activity's parent activity within the app's logical hierarchy. The system uses this value to implement default navigation behaviors, such as Up
navigationon Android 4.1 (API level 16) and higher. You can provide the same navigation behaviors for older versions of Android by using the Support
Library and adding the
<meta-data>
element
as shown here.

Note: Your Android SDK should already include the latest Android Support Library. It's included with the ADT Bundle but if you're using a different IDE, you should have installed it during the Adding
Platforms and Packages step. When using the templates in Eclipse, the Support Library is automatically added to your app project (you can see the library's JAR file listed under Android Dependencies). If you're not using Eclipse, you need to manually
add the library to your project—follow the guide for setting
up the Support Library then return here.
If you're developing with Eclipse, you can run the app now, but not much happens. Clicking the Send button starts the second activity but it uses a default "Hello world" layout provided by the template. You'll soon
update the activity to instead display a custom text view, so if you're using a different IDE, don't worry that the app won't yet compile.


Receive the Intent

Every
Activity
is
invoked by an
Intent
,
regardless of how the user navigated there. You can get the
Intent
that
started your activity by calling
getIntent()
and
retrieve the data contained within it.
In the
DisplayMessageActivity
class’s
onCreate()
method,
get the intent and extract the message delivered by
MainActivity
:
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);


Display the Message

To show the message on the screen, create a
TextView
widget
and set the text using
, int, int)]setText()
.
Then add the
TextView
as
the root view of the activity’s layout by passing it to
setContentView()
.
The complete
onCreate()
method
for
DisplayMessageActivity
now looks like this:
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Get the message from the intent
    Intent intent = getIntent();
    String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);

    // Create the text view
    TextView textView = new TextView(this);
    textView.setTextSize(40);
    textView.setText(message);

    // Set the text view as the activity layout
    setContentView(textView);
}



启动另一个活动

上一页下一页


这节课教你

响应发送按钮
建立一个Intent
启动第二个活动
创建第二个活动
收到意向
显示消息


你也应该阅读

安装SDK

完成后上一课,你有一个应用程序,展示活动(单屏)与文本字段和一个按钮。在本课中,您将添加一些代码,以
MainActivity
,当用户点击发送按钮启动一个新的活动。


响应发送按钮

为了响应按钮的上单击事件,打开
activity_main.xml
布局文件,并添加
Android版
 ​​本:的onClick
属性到
的<button>
元素:
<Button 
    android:layout_width = "wrap_content" 
    android:layout_height = "wrap_content" 
    android:text = "@string/button_send" 
    android:onClick = "sendMessage"  />

机器人:的onClick
属性的值,
“的sendMessage”
,是在你的活性的方法,当用户单击该按钮,系统调用的名称。
打开
MainActivity
类(位于项目
的src /
目录下),并添加相应的方法:
/ **当用户点击发送按钮* /被叫
公共 无效的sendMessage (查看视图) { 
    / /做一些响应按钮
}

这需要你导入
浏览
类:
进口机器人。视图。查看;


提示:在Eclipse中,按Ctrl + Shift + O导入缺失类(Cmd的+ SHIFT + O在Mac)。
为了使系统这个方法匹配给定的方法名
的android:的onClick
,签名必须完全如图所示。具体地讲,该方法必须:

是公开的
有一个void返回值
有一个
视图
作为唯一的参数(这将是
查看
被点击)

接下来,您将填写此方法来读取文本字段的内容和提供的文本到另一个活动。


建立一个Intent

一个
意图
是一个对象,它提供独立的运行时组件(如两项活动)之间的绑定。该
意向书
表示应用程序的“意图做一些事情。” 您可以使用意图为各种各样的任务,但大多数时候他们已经习惯了启动另一个活动。
里面
的sendMessage()
方法,创建一个
意图
,开始称为活动
DisplayMessageActivity

意向意图=  新的 意图(这, DisplayMessageActivity 。类);

这里使用的构造函数有两个参数:

一个
上下文
作为其第一个参数(
是因为该
活动
是类的一个子类
上下文

的应用程序组件的,本系统应交付的
意图
(在这种情况下,应启动的活性)


发送意图的其他应用程序

在这一课中创建的目的是什么认为是明确的意图,因为
意图
指定确切的应用程序组件的意图应该放在首位。然而,意图也可以是隐式的,在这种情况下,
意图
不指定所希望的组分,但是允许在设备上安装的任何应用程序,只要它满足元数据规范是在各个指定的动作来响应意图
意图
参数。欲了解更多信息,请参见有关类与其他应用程序交互

注:本参考
DisplayMessageActivity
会,如果你使用的是IDE,比如Eclipse,因为类还不存在引发错误。忽略该错误吧; 你很快就会创建类。
一个意图,不仅可以让你启动另一个活动,但它可以携带数据包的活性。里面
的sendMessage()
方法,使用
findViewById()
来获取
的EditText
元素和它的文本值添加到意图:
Intent intent =  new  Intent ( this ,  DisplayMessageActivity . class ); 
EditText editText =  ( EditText ) findViewById ( R . id . edit_message ); 
String message = editText . getText (). toString (); 
intent . putExtra ( EXTRA_MESSAGE , message );


注意: 您现在需要的import语句
android.content.Intent
android.widget.EditText
。你会定义
EXTRA_MESSAGE
在某一时刻不变。
一个
意图
可以进行各种数据类型作为键-值对所谓的集合群众演员。该
putExtra()
方法将键名的第一个参数,该值在第二个参数。
为了使下一个活动来查询额外的数据,你应该使用一个公共常量定义键你的意图的额外费用。因此,添加
EXTRA_MESSAGE
定义到顶部
MainActivity
类:
public  class  MainActivity  extends  Activity  { 
    public  final  static  String EXTRA_MESSAGE =  "com.example.myfirstapp.MESSAGE" ; 
    ... 
}

这通常是一个很好的做法使用你的应用程序的包名作为前缀来定义额外的意图键。这将确保它们是唯一的,如果你的应用程序与其他应用程序进行交互。


启动第二个活动

要启动一个活动,叫
的startActivity()
并传递给它你的
意图
。该系统接收此呼叫并启动实例
活动
由指定的
意图

有了这个新的代码,完整
的sendMessage(),
这是由发送按钮调用的方法现在看起来像这样:
/ **当用户点击发送按钮时调用*/ 
public  void sendMessage ( View view )  { 
    Intent intent =  new  Intent ( this ,  DisplayMessageActivity . class ); 
    EditText editText =  ( EditText ) findViewById ( R . id . edit_message ); 
    String message = editText . getText (). toString (); 
    intent . putExtra ( EXTRA_MESSAGE , message ); 
    startActivity ( intent ); 
}

现在,您需要创建
DisplayMessageActivity
为了班级这个工作。


创建第二个活动



图1:在Eclipse的新的活动向导。

使用Eclipse创建一个新的活动:

单击新建

工具栏上。
在出现的窗口中,打开Android的文件夹并选择Android的活动。单击下一步
选择BlankActivity,然后单击下一步
在活动的详细信息填写:

项目:MyFirstApp
活动名称:DisplayMessageActivity
版面名称:activity_display_message
标题:我的留言
分层家长:com.example.myfirstapp.MainActivity
导航类型:无

单击Finish(完成)

如果您使用的是不同的IDE或命令行工具,创建一个名为新文件
DisplayMessageActivity.java
在项目的
的src /
目录下,同原来的
MainActivity.java
文件。
打开
DisplayMessageActivity.java
文件。如果你使用Eclipse来创建此活动:

这个类已经包含了所需的实现
的onCreate()
方法。
另外还有的实现
onCreateOptionsMenu()
方法,但你不会需要它为这个应用程序,您可以将其删除。
还有的实现
onOptionsItemSelected()
负责处理的操作栏中的行为上的行为。保持这个事情是这样的。

因为
动作条
的API仅适用于
蜂窝
(API级别11)和更高的,你必须添加周围的条件
getActionBar()
方法来检查当前平台的版本。此外,您必须添加
@
 SuppressLint(“NewApi”)
标签到
的onCreate()
方法,以避免皮棉错误。
DisplayMessageActivity
类现在看起来应该像这样:
public  class  DisplayMessageActivity  extends  Activity  { 

    @SuppressLint ( "NewApi" ) 
    @Override 
    protected  void onCreate ( Bundle savedInstanceState )  { 
        super . onCreate ( savedInstanceState ); 
        setContentView ( R . layout . activity_display_message ); 

        //确保我们在蜂窝或更高版本上运行使用的ActionBar的API 
        ,如果 (建造。版本。SDK_INT > =  生成。VERSION_CODES 。蜂窝) { 
            / /显示向上按钮的动作bar. 
            getActionBar (). setDisplayHomeAsUpEnabled ( true ); 
        } 
    } 

    @Override 
    public  boolean onOptionsItemSelected ( MenuItem item )  { 
        switch  ( item . getItemId ())  { 
        case android . R . id . home : 
            NavUtils . navigateUpFromSameTask ( this ); 
            return  true ; 
        } 
        return  super . onOptionsItemSelected ( item ); 
    } 
}

如果您使用的IDE比其他的Eclipse,更新您的
DisplayMessageActivity
与上面的代码类。
的所有子类
活动
必须实现
的onCreate()
方法。创建活动的新实例时,系统调用这个。这种方法是,你必须定义与活动布局
的setContentView()
方法,并是你应该的活动部件进行初始设置。

注:如果您使用的是IDE比其他的Eclipse,你的项目不包含
activity_display_message
那的要求布置
的setContentView() 
。这是确定的,因为你会在以后更新此方法并不会使用该布局。


添加标题字符串

如果你使用Eclipse,则可以跳到下一章节,因为模板提供了新的活动的标题字符串。
如果你使用的是IDE比其他的Eclipse,新活动的标题添加到
的strings.xml
文件:
<resources> 
    ... 
    <字符串 名称= “title_activity_display_message” > 我的留言</字符串> 
</资源>


它添加到清单

所有活动都必须在你的manifest文件,声明
AndroidManifest.xml中
,使用
<activity>
元素。
当您使用Eclipse工具来创建活动,它会创建一个默认项。如果您使用的是不同的IDE,你需要自己添加清单条目。它应该看起来像这样:
<application ... > 
    ... 
    <activity 
        android:name = "com.example.myfirstapp.DisplayMessageActivity" 
        android:label = "@string/title_activity_display_message" 
        android:parentActivityName = "com.example.myfirstapp.MainActivity"  > 
        <meta-data 
            android:name = "android.support.PARENT_ACTIVITY" 
            android:value = "com.example.myfirstapp.MainActivity"  /> 
    </activity> 
</application>

机器人:parentActivityName
属性声明了应用程序的逻辑层次结构中本次活动的父活动的名称。该系统使用此值来实现默认的导航行为,如向上导航在Android
4.1(API级别16)和较高的。您可以通过使用提供相同的导航行为较旧版本的Android 支持库和添加
<meta-data>
元素,如下所示。

注:您的Android SDK中应该已经包括了最新的Android支持库。它包含在ADT捆绑,但如果您使用的是不同的IDE,你应该在安装它 添加平台和软件包的一步。当使用Eclipse中的模板,支持库会自动添加到您的应用程序的项目(你可以看到所列出的库的JAR文件Android的依赖关系)。如果你不使用Eclipse,你需要到图书馆手动添加到您的项目遵循的指导设立的支持库 ,然后返回这里。
如果您正在开发使用Eclipse,你就可以执行应用程序,但没有太大的反应。点击发送按钮启动第二活动,但它采用的是默认的“Hello world”的布局由模板提供的。你很快就会更新,而不是来显示自定义文本视图的活性,因此,如果您使用的是不同的IDE,不要担心,该应用程序将尚未编译。


收到意向

每一个
活动
是由调用
意图
,不管用户如何导航那里。你可以得到的
意图
是开始你的活动通过调用
getIntent()
和获取其中包含的数据。
DisplayMessageActivity
类的
的onCreate()
方法,得到的意图,并提取由交付该消息
MainActivity

意向意图= getIntent (); 
字符串消息= 意图。getStringExtra (MainActivity 。EXTRA_MESSAGE );


显示消息

要在屏幕上显示的消息,创建一个
TextView的
小部件,并使用设置文本
, int, int)]的setText() 
。然后添加
的TextView
通过它传递给作为活动的布局的根视图
的setContentView() 

完整
的onCreate()
方法
DisplayMessageActivity
现在看起来像这样:
@覆盖
公共 无效的onCreate (捆绑savedInstanceState ) { 
    超。的onCreate (savedInstanceState ); 

    / /获取从意图的消息
    意向意图= getIntent (); 
    字符串消息= 意图。getStringExtra (MainActivity 。EXTRA_MESSAGE ); 

    / /创建文本视图
    TextView的text查看=  新 TextView的(本); 
    text查看。setTextSize (40 ); 
    text查看。的setText (消息); 

    / /设置文本视图作为活动布局
    的setContentView (text查看); 
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐