Create a Project with Eclipse
- Click New in the toolbar.
- In the window that appears, open the Android folder, select Android Application Project, and click Next.
- Fill in the form that appears:
- Application Name is the app name that appears to users. For this project, use "My First App."
- Project Name is the name of your project directory and the name visible in Eclipse.
- Package Name is the package namespace for your app (following the same rules as packages in the Java programming language). Your package name must be unique across all packages installed on the Android system. For this reason, it's generally best if you use a name that begins with the reverse domain name of your organization or publisher entity. For this project, you can use something like "com.example.myfirstapp." However, you cannot publish your app on Google Play using the "com.example" namespace.
- Minimum Required SDK is the lowest version of Android that your app supports, indicated using the API level. To support as many devices as possible, you should set this to the lowest version available that allows your app to provide its core feature set. If any feature of your app is possible only on newer versions of Android and it's not critical to the app's core feature set, you can enable the feature only when running on the versions that support it (as discussed in Supporting Different Platform Versions). Leave this set to the default value for this project.
- Target SDK indicates the highest version of Android (also using the API level) with which you have tested with your application.
As new versions of Android become available, you should test your app on the new version and update this value to match the latest API level in order to take advantage of new platform features.
- Compile With is the platform version against which you will compile your app. By default, this is set to the latest version of Android available in your SDK. (It should be Android 4.1 or greater; if you don't have such a version available, you must install one using the SDK Manager). You can still build your app to support older versions, but setting the build target to the latest version allows you to enable new features and optimize your app for a great user experience on the latest devices.
- Theme specifies the Android UI style to apply for your app. You can leave this alone.
Click Next.
- On the next screen to configure the project, leave the default selections and click Next.
- The next screen can help you create a launcher icon for your app.
You can customize an icon in several ways and the tool generates an icon for all screen densities. Before you publish your app, you should be sure your icon meets the specifications defined in the Iconography design guide.
Click Next.
- Now you can select an activity template from which to begin building your app.
For this project, select BlankActivity and click Next.
- Leave all the details for the activity in their default state and click Finish.
创建一个Eclipse的项目
- 单击新建 工具栏上。
- 在出现的窗口中,打开Android的文件夹,选择Android的应用程序项目,然后单击下一步。
- 在出现的表单填写:
- 应用程序名称是出现给用户的应用程序名称。对于这个项目,使用“MyFirstApp”
- 项目名称就是你的项目目录的名称,名称在Eclipse中可见。
- 包名称是包的命名空间为您的应用程序(遵循相同的规则,在Java编程语言包)。你的包名称必须在安装了Android系统上的所有软件包唯一的。出于这个原因,它通常最好的,如果您使用的开始与您的组织或出版者实体的反向域名名称。对于这个项目,你可以使用类似“com.example.myfirstapp。” 但是,你不能在谷歌播放使用为“com.example”命名空间发布你的应用程序。
- 最低要求的SDK是Android的最低版本,您的应用程序的支持,使用指示的API级别。为了支持尽可能多的设备越好,你应该将其设置为可用,可以让您的应用程序,以提供其核心功能集的最低版本。如果您的应用程序的任何功能只能在较新版本的Android,它不是以应用程序的核心功能集的关键,你可以在支持它的版本只运行时(如在讨论启用该功能支持不同的平台版本)。将它设置为默认值,为这个项目。
- 目标SDK中表示最高版本的Android(也使用的 API级别),您已与您的应用程序进行测试。
由于Android的新版本可用,您应该测试应用程序的新版本,并更新此值,以便利用新的平台功能利用最新的API级别相匹配。
- 编译为平台版本针对您将编译您的应用程序。默认情况下,此选项设置为可用的Android的最新版本,在你的SDK。(这应该是Android的4.1或更高版本,如果你没有这样的版本,您必须使用安装一个SDK管理器)。你还可以建立自己的应用程序来支持旧版本,但构建目标设定到最新版本允许您启用新功能和优化您的应用程序的最新的设备出色的用户体验。
- 主题指定了Android的UI风格申 请您的应用程序。你可以不理会这一点。
单击下一步。
- 在下一个屏幕,用于配置项目,保留默认选项,然后单击 下一步。
- 下一个屏幕可以帮助你创建你的应用程序的起动器图标。
您可以通过多种方式自定义的图标和工具生成所有的屏幕密度的图标。在您发布您的应用程序,你应该确保你的图标符合该定义的规范影像学 设计指南。
单击下一步。
- 现在,您可以选择要开始建立你的应用程序的活动模板。
对于这个项目,选择BlankActivity然后单击下一步。
- 离开所有的细节在其默认状态的活动,并单击 Finish(完成)。
THIS LESSON TEACHES YOU TO
YOU SHOULD ALSO READ
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:
-
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 theandroid:minSdkVersion
andandroid: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="19" /> ... </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. -
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. -
Contains several sub-directories for
app resources. Here are just a few:
- 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.
- Directory for files that define your app's user interface.
- Directory for other various XML files that contain a collection of resources, such as string and color definitions.
drawable-hdpi/
layout/
values/
AndroidManifest.xml
src/
res/
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.
如果你是按照上一课创建一个Android项目,它包含了“Hello World”的源文件,让您可以立即运行该应用程序的缺省设置。
您如何运行你的应用程序依赖于两件事情:你是否有一个真正的Android设备,并不管你是使用Eclipse。本课程将告诉您如何安装和真实设备,并在Android模拟器上运行你的应用程序,并在两种情况下使用Eclipse或命令行工具。
在你运行你的应用程序,你应该知道,在Android项目的几个目录和文件:
-
该
清单文件描述了应用程序的基本特性,并定义它的每一个组成部分。您将了解在这个文件中各项声明,当你阅读更多培训课程。
其中最重要的内容资讯清单应包括的是
<uses-sdk>
元素。此声明与使用不同版本的Android您的应用程序的兼容性的android:minSdkVersion
和Android版 本:targetSdkVersion
属性。为了您的第一个应用程序,它看起来应该像这样:<manifest xmlns:android = "http://schemas.android.com/apk/res/android" ... > <uses-sdk android:minSdkVersion = "8" android:targetSdkVersion = "19" /> ... </manifest>
你应该总是设置
的android:targetSdkVersion
尽可能高,并在相应的平台版本测试您的应用程序。欲了解更多信息,请阅读支持不同的平台版本。 -
目录为你的应用程序的主源文件。默认情况下,它包含一个
活动
运行时,您的应用程序使用的应用程序图标启动类。 -
包含几个子目录的
应用程序资源。这里仅仅是几个例子:
- 目录可绘制对象(如位图)是专为高密度(HDPI)屏幕。其他可绘制目录包含专为其他屏幕密度的资产。
- 目录定义您的应用程序的用户界面文件。
- 目录中包含资源的集合等各种XML文件,例如字符串,颜色定义。
绘制-HDPI /
布局/
值/
AndroidManifest.xml文件
SRC /
业绩/
当你建立并运行默认的Android应用程序,默认活动
类启动并加载一个布局文件,上面写着的“Hello World”。其结果是平平淡淡,但您了解如何运行你的程序,你开始开发之前,这一点很重要。
THIS LESSON TEACHES YOU TO
- Create a Linear Layout
- Add a Text Field
- Add String Resources
- Add a Button
- Make the Input Box Fill in the Screen Width
YOU SHOULD ALSO READ
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.
Alternative Layouts
Declaring your UI layout in XML rather than runtime code is useful for several reasons, but it's especially important so you can create different layouts for different screen sizes. For example, you can create two versions of a layout and tell the system to use one on "small" screens and the other on "large" screens. For more information, see the class about Supporting Different Devices.
In this lesson, you'll create a layout in XML that includes a text field and a button. In the following lesson, you'll respond when the button is pressed by sending the content of the text field to another activity.
Create a Linear Layout
Open the fragment_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 fragment_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 fragment_main.xml
file with aRelativeLayout
root view and a TextView
child view.
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:
<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.
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 theandroid:hint
attribute. You can also create arbitrary resource IDs that you associate with a view using theandroid: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:
-
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'sgen/R.java
file that refers to theEditText
element. Once the resource ID is declared once this way, other references to the ID do not need the plus sign. Using the plus sign is necessary only when specifying a new resource ID and not needed for concrete resources such as strings or layouts. See the sidebox for more information about resource objects. -
Instead of using specific sizes for the width and height, the
"wrap_content"
value specifies that the view should be only as big as needed to fit the contents of the view. If you were to instead use"match_parent"
, then theEditText
element would fill the screen, because it would match the size of the parentLinearLayout
. For more information, see the Layouts guide. -
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 asid
orstring
), so using the same name does not cause collisions.
android:id
android:layout_width
and
android:layout_height
android:hint
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.
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 theEditText
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.
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.
对于一个Android应用程序的图形用户界面使用的层次结构建立视图
和视图组
对象。查看
对象通常是UI小部件,如按钮或 文本字段和视图组
对象是不可见的视图的容器定义如何的子视图的布局,如在网格或垂直列表。
Android提供了对应的子类的XML词汇表视图
和视图组
,因此您可以在XML中使用的UI元素的层次结构中定义你的用户界面。
另类布局
有几个原因,宣布在XML中,而不是运行时代码的UI布局是非常有用的,但它是特别重要的,这样你可以创建不同的布局不同的屏幕尺寸。例如,您可以创建两个版本的布局,并告诉系统使用一个关于“小”屏幕和其他的“大”屏幕。欲了解更多信息,请参见有关类支持不同的设备。
在本课中,您将创建一个XML格式的布局,其中包括一个文本字段和一个按钮。在接下来的课程中,将按钮时,通过发送文本字段的内容到另一个活动按下作出回应。
创建一个线性布局
打开fragment_main.xml
从文件RES /布局/
目录下。
注:在Eclipse中,当你打开一个布局文件,你第一次显示的图形布局编辑器。这是一个编辑器,可帮助您使用所见即所得的工具构建布局。在这一课中,你将直接与XML的,所以点击fragment_main.xml选项卡,在屏幕底部打开XML编辑器。
当你创建这个项目,你选择了BlankActivity模板包括 fragment_main.xml
与文件RelativeLayout
根视图和一个TextView的
子视图。
首先,删除<TextView>
元素和改变<RelativeLayout>
元素<LinearLayout>
。然后添加 机器人:定位
属性,并将其设置为“横向”
。结果看起来像这样:
<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”
。该值声明该视图应该扩大它的宽度或高度来匹配父视图的宽度或高度。
有关布局属性的详细信息,请参阅布局指南。
添加一个文本字段
要创建一个用户可编辑的文本字段,添加一个<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文件
每次编译您的应用程序的时间。你不应该手动修改这个文件。
欲了解更多信息,请阅读指南,提供了资源。
关于这些属性:
-
这提供了一个独特的标识符视图,您可以用它来从你的应用程序代码,如阅读和操作对象引用的对象(你会看到这个在下一课)。
at符号(
@
),当你指的是从XML的任何资源对象是必需的。它后面的资源类型(ID
在这种情况下),斜线,则该资源名称(edit_message
)。加号(
+
资源类型之前)是必要的,只有当你定义一个资源ID的第一次。当你编译的应用程序,SDK工具使用ID名称在项目中创建一个新的资源ID根/ R.java文件
是指文件的EditText
元素。一旦资源ID被宣告一次通过这种方式,其他参考文献的编号并不需要的加号。指定一个新的资源ID,而不是需要具体的资源,如字符串或布局仅当使用加号是必要的。见sidebox的有关资源对象的详细信息。 -
除了 使用特定大小的宽度和高度,在
“wrap_content”
值指定为需要调整视图内容的视图应该只为大。如果你要改用“match_parent”
,那么的EditText
元素将填满整个屏幕,因为它会匹配父的大小的LinearLayout
。欲了解更多信息,请参阅 布局指南。 -
这是一个默认的字符串显示在文本字段为空。而不是使用硬编码字符串作为值时,
“@字符串/ edit_message”
值指的是在一个单独的文件中定义的字符串资源。因为这是指一种具体的资源(不只是一个标识符),它不需要加号。但是,因为你还没有定义的字符串资源,但你会看到在第一次编译器错误。您将通过定义字符串解决这个问题在下一节。注:此字符串资源具有相同的名称作为元素的ID:
edit_message
。但是,引用资源由资源类型(如始终范围ID
或字符串
),所以使用相同的名称不会引起冲突。
机器人:ID
机器人:layout_width
和
机器人:layout_height
机器人:提示
添加字符串资源
当你需要在用户界面中添加文字,您应该总是指定每个字符串作为资源。字符串资源,让您可以管理在一个位置,这使得它更容易找到并更新文本的所有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。
这工作得很好了按钮,但没有得到很好的文本字段,因为用户可能会输入一些较长。所以,这将是很好的填补未使用的屏幕的宽度与文本字段。你可以在里面一个做到这一点 的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
元素。
这里是你的完整布局文件现在应该怎么看:
<?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中,单击运行在工具栏中。
- 或者在命令行,将目录更改为你的Android项目的根目录,然后执行:
蚂蚁调试 的adb安装斌/ MyFirstApp - 调试。apk文件
继续下一课来学习如何应对按下按钮,从文本字段读取内容,启动另一个活动,等等。
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
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 thefragment_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 }
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 theView
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). TheIntent
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);
This requires that you import the Intent
class:
import android.content.Intent;
Tip: In Eclipse, press Ctrl + Shift + O to import missing classes (Cmd + Shift + O on Mac).
The constructor used here takes two parameters:
- A
Context
as its first parameter (this
is used because theActivity
class is a subclass ofContext
) - The
Class
of the app component to which the system should deliver theIntent
(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 thesendMessage()
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 an import statement forandroid.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 ActionBarActivity { 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
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
- Fragment Layout Name: fragment_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. You will update the implementation of this method later. - 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. - There's also a
PlaceholderFragment
class that extendsFragment
. You will not need this class in the final version of this activity.
Fragments decompose application functionality and UI into reusable modules. For more information on fragments, see the Fragments API Guide. The final version of this activity does not use fragments.
Note: Your activity may look different if you did not use the latest version of the ADT plugin. Make sure you install the latest version of the ADT plugin to complete this tutorial.
The DisplayMessageActivity
class should now look like this:
public class DisplayMessageActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_display_message); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(R.id.container, new PlaceholderFragment()).commit(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } /** * A placeholder fragment containing a simple view. */ public static class PlaceholderFragment extends Fragment { public PlaceholderFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_display_message, container, false); return rootView; } } }
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 byMainActivity
:
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 setText()
. Then add theTextView
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); }
You can now run the app. When it opens, type a message in the text field, click Send, and the message appears on the second activity.
That's it, you've built your first Android app!
To learn more, follow the link below to the next class.
完成后上一课,你有一个应用程序,展示活动(单屏)与文本字段和一个按钮。在本课中,您将添加一些代码,以MainActivity
,当用户点击发送按钮启动一个新的活动。
响应发送按钮
为了响应按钮的上单击事件,打开fragment_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 (查看视图) { / /做一些响应按钮 }
为了使系统这个方法匹配给定的方法名的android:的onClick
,签名必须完全如图所示。具体地讲,该方法必须:
接下来,您将填写此方法来读取文本字段的内容和提供的文本到另一个活动。
建立一个Intent
一个意图
是一个对象,它提供独立的运行时组件(如两项活动)之间的绑定。该意向书
表示应用程序的“意图做一些事情。” 您可以使用意图为各种各样的任务,但大多数时候他们已经习惯了启动另一个活动。
里面的sendMessage()
方法,创建一个意图
,开始称为活动DisplayMessageActivity
:
意向意图= 新的 意图(这, DisplayMessageActivity 。类);
这需要你导入意图
类:
进口机器人。内容。意图;
提示:在Eclipse中,按Ctrl + Shift + O导入缺失类(Cmd的+ SHIFT + O在Mac)。
这里使用的构造函数有两个参数:
注:本参考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.widget.EditText
。你会定义EXTRA_MESSAGE
在某一时刻不变。
一个意图
可以进行各种数据类型作为键-值对所谓的集合群众演员。该putExtra()
方法将键名的第一个参数,该值在第二个参数。
为了使下一个活动来查询额外的数据,你应该使用一个公共常量定义键你的意图的额外费用。因此,添加EXTRA_MESSAGE
定义到顶部MainActivity
类:
public class MainActivity extends ActionBarActivity { 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
为了班级这个工作。
创建第二个活动
使用Eclipse创建一个新的活动:
- 单击新建 工具栏上。
- 在出现的窗口中,打开Android的文件夹并选择Android的活动。单击下一步。
- 选择BlankActivity,然后单击下一步。
- 在活动的详细信息填写:
- 项目:MyFirstApp
- 活动名称:DisplayMessageActivity
- 版面名称:activity_display_message
- 片段布局名称:fragment_display_message
- 标题:我的留言
- 分层家长:com.example.myfirstapp.MainActivity
- 导航类型:无
单击Finish(完成)。
如果您使用的是不同的IDE或命令行工具,创建一个名为新文件 DisplayMessageActivity.java
在项目的的src /
目录下,同原来的MainActivity.java
文件。
打开DisplayMessageActivity.java
文件。如果你使用Eclipse来创建此活动:
- 这个类已经包含了所需的实现
的onCreate()
方法。稍后您将更新此方法的实现。 - 另外还有的实现
onCreateOptionsMenu()
方法,但你不会需要它为这个应用程序,您可以将其删除。 - 还有的实现
onOptionsItemSelected()
负责处理的操作栏中的行为上的行为。保持这个事情是这样的。 - 还有一个
PlaceholderFragment
扩展类的片段
。在本次活动的最终版本你不需要这个类。
片段分解的应用功能和用户界面到可重用的模块。有关片段的更多信息,请参见碎片API指南。本次活动的最终版本不使用碎片。
注:您的活动可能会有所不同,如果你没有使用ADT插件的最新版本。请确保您安装了最新版本的 ADT插件来完成本教程。
该DisplayMessageActivity
类现在看起来应该像这样:
手柄动作栏项目点击这里。操作栏会 / /自动在首页/向上按钮的点击处理,只要 / /当你在指定一个父活动 包含一个简单的占位符片段
如果您使用的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的
小部件,并使用设置文本的setText()
。然后添加的TextView
通过它传递给作为活动的布局的根视图的setContentView()
。
完整的onCreate()
方法DisplayMessageActivity
现在看起来像这样:
@覆盖 公共 无效的onCreate (捆绑savedInstanceState ) { 超。的onCreate (savedInstanceState ); / /获取从意图的消息 意向意图= getIntent (); 字符串消息= 意图。getStringExtra (MainActivity 。EXTRA_MESSAGE ); / /创建文本视图 TextView的text查看= 新 TextView的(本); text查看。setTextSize (40 ); text查看。的setText (消息); / /设置文本视图作为活动布局 的setContentView (text查看); }
现在,您可以运行应用程序。当它打开时,输入邮件中的文本字段,点击发送,并在第二个活动出现的消息。
就是这样,你已经建立你的第一个Android应用程序!