翻译真不容易啊!给自己加个油
Running Your App
This lesson teaches you to
- Run on a Real Device
- Run on the Emulator
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.
如果接着上一课创建了android工程,那么包括默认的"Hello World"集合资源文件允许你立刻运行。
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.
如何运行app取决于两件事,是否有个真机或是否使用eclipse.这个现实如何下载和运行app在真机或android emulator和用eclipse或命令行工具在两种情况下。
Before you run your app, you should be aware of a few directories and files in the Android project:
在运行app之前,需要了解在android工程中的几个目录和文件
AndroidManifest.xmlThe 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.载货单文件描述app基本基本特征和定义了每个组件。你将学习各种各样定义在这个文件里面当你读到更多的训练课程。src/Directory for your app's main source files. By default, it includes an Activityclass that runs when your app is launched using the app icon.app主要源文件目录。默认,包括了activity类,类运行当app触发被app图标。res/Contains several sub-directories for app resources. Here are just a few:包括很多子目录的app资源,这只有举例几个: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.drawable对象目录,给high-density设计的。其它drawable目录包含有用的设计给其它的屏幕。layout/Directory for files that define your app's user interface.文件目录包括app用户接口。values/Directory for other various XML files that contain a collection of resources, such as string and color definitions.其它各种各样的xml文件目录包含资源计划,比如string和颜色定义。When you build and run the default Android app, the defaultActivityclass 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 app,默认活动类开始,并且载入layout文件,文件运行"Hello World"。结果不兴奋,但是对于理解如何运行app是很重要的,在你开始开发之前。
Run on a Real Device
If you have a real Android-powered device, here's how you can install and run your app:
如果你有个真的android设备,下面介绍如何下载并且运行app:
- Plug in your device to your development machine with a USB cable. If you're developing on Windows, you might need to install the appropriate USB driver for your device. For help installing drivers, see the OEM USB Drivers document. 用USB线连接设备到开发机器。如何你正在windows开发,你需要下载合适usb驱动为你的设备。为了帮助下载设备。查看OEM USB DRIVERS
- Enable USB debuggingon your device.
- On most devices running Android 3.2 or older, you can find the option under Settings > Applications > Development.
- On Android 4.0 and newer, it's in Settings > Developer options.
Note: On Android 4.2 and newer, Developer options is hidden by default. To make it available, go to Settings > About phone and tap Build number seven times. Return to the previous screen to find Developer options
使USB DEBUGGING 在设备上有用。
在很多android3.2或更老的设备,你能找到选项在settings-->applications-->development
在android4.0和更新的设备上。developer option是默认隐藏的。为了可用,需要在 settings -->about phone和 轻按build number7次.返回前一屏幕找到developer options
To run the app from Eclipse, open one of your project's files and click Run from the toolbar. Eclipse installs the app on your connected device and starts it.
为了运行从eclipse上的app,打开一个工程文件,从工具栏点击run 。eclipse下载app在你连接设备上,开始运行。
Or to run your app from a command line:
或者从命令行运行app
- Change directories to the root of your Android project and execute:
ant debug
- Make sure the Android SDKplatform-tools/directory is included in yourPATHenvironment variable, then execute:
adb install bin/MyFirstApp-debug.apk
- On your device, locate MyFirstActivity and open it.
1.改变目录到android 工程根目录,运行 ant debug
2.确定android sdkplatform-tools/目录包括在PATH 环境变量,然后执行:
adb install bin/*.apk
3.在设备上,载入MyFirstActivity打开它。
That's how you build and run your Android app on a device! To start developing, continue to the next lesson.
Run on the Emulator
Whether you're using Eclipse or the command line, to run your app on the emulator you need to first create an Android Virtual Device (AVD). An AVD is a device configuration for the Android emulator that allows you to model different devices.
不论是使用eclipse或者命令行,运行app在emulator。你需要第一次创建avd。AVD是一个设备,配置android emulator,允许你塑造不同设备。
Figure 1. The AVD Manager showing a few virtual devices.
To create an AVD:
- Launch the Android Virtual Device Manager:
- In Eclipse, click Android Virtual Device Manager from the toolbar.
- From the command line, change directories to<sdk>/tools/and execute:
android avd
- In the Android Virtual Device Manager panel, click New.
- Fill in the details for the AVD. Give it a name, a platform target, an SD card size, and a skin (HVGA is default).
- Click Create AVD.
- Select the new AVD from the Android Virtual Device Manager and clickStart.
- After the emulator boots up, unlock the emulator screen.
To run the app from Eclipse, open one of your project's files and click Run from the toolbar. Eclipse installs the app on your AVD and starts it.
AVD管理者显示几个虚拟设备。
创建一个avd:
1.在eclipse里,从工具栏点击Android Virtual Device Manager 。
2.从命令行,改变目录到<sdk>/tools/,并且执行 : android avd
Or to run your app from the command line:
- Change directories to the root of your Android project and execute:
ant debug
- Make sure the Android SDKplatform-tools/directory is included in yourPATHenvironment variable, then execute:
adb install bin/MyFirstApp-debug.apk
- On the emulator, locate MyFirstActivity and open it.
That's how you build and run your Android app on the emulator! To start developing, continue to the next lesson.
Building a Simple User Interface
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 ofViewandViewGroupobjects.Viewobjects are usually UI widgets such as buttons ortext fields andViewGroupobjects 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 ofViewandViewGroupso you can define your UI in XML using a hierarchy of UI elements.
android app图形用户界面是用view和viewgroup对象等级.view对象经常使用UI 部件比如按钮或者文本域,viewgroup对象是不可见的view,包含定义子views如何布局,比如grid或者垂直list.
android提供xml词汇量相当于ViewandViewGroup子类,你能定义UI在xml文件,是一个UI元素等级
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.
定义UI布局在xml文件比运行代码有用有几个原因,但特别重要的是你能创建不同布局为不同屏幕大小。比如,你能创建两个不同的布局,告诉系统使用其中一个在“small”屏幕和其它在“large”屏幕。更多信息,查看支持不同设备类。
Figure 1. Illustration of howViewGroupobjects form branches in the layout and contain otherViewobjects.
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.
ViewGroup对象如何分支在布局和包含其它view对象插图。在这课,你将在xml创建布局,包含一个文件域和按钮。在接下来的课,你将回应当按钮按下,发送文本于内容到另外活动。
Create a Linear Layout
Open theactivity_main.xmlfile from theres/layout/directory.
从res/layout/目录打开activity_main.xml文件。
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.
在eclipse,当你打开布局文件,你看到的是图形布局编辑器。是一个能帮你创建布局的编辑器,用WYSIWYG工具。在这课,你能够直接用xml工具工作,所以点击activity_main.xml标签在屏幕下方打开xml编辑器。
The BlankActivity template you used to start this project creates theactivity_main.xmlfile with aRelativeLayoutroot view and aTextViewchild view.
用空活动临时文件开始工作去创建theactivity_main.xml文件,文件有RelativeLayout根视图和TextView子视图。
First, delete the<TextView>element and change the<RelativeLayout>element to<LinearLayout>. Then add theandroid:orientation attribute and set it to"horizontal". The result looks like this:
首先,删除<TextView>元素,改变<RelativeLayout>元素到<LinearLayout>。增加android:orientation属性,设置为"horizontal".
<?xml version="1.0" encoding="utf-8"?> <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>
LinearLayoutis a view group (a subclass ofViewGroup) that lays out child views in either a vertical or horizontal orientation, as specified by the android:orientation attribute. Each child of aLinearLayoutappears on the screen in the order in which it appears in the XML.
LinearLayout是一个视图组(viewgroup子类),排列子视图在垂直或水平定会,特殊by android:orientation属性。每个LinearLayout子属性出现在屏幕,排序在它出现在xml的位置。
The other two attributes, android:layout_width and android:layout_height, are required for all views in order to specify their size.
另外两个属性,android:layout_width and android:layout_height 是需要存在所有视图去定义大小。
Because theLinearLayoutis 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.
因为LinearLayout是一个布局中的根视图,它应该被填充在整个屏幕区域,通过设置宽,高为match_parent,对于app是可用的。这个值声明视图需要扩展宽和高到匹配父子类的宽和高。
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>.
为了创建一个用户可编辑的文本域,增加<EditText>元素在<LinearLayout>里面。
Like everyViewobject, you must define certain XML attributes to specify theEditTextobject's properties. Here’s how you should declare it inside the<LinearLayout>element:
就像每个view对象,你需要定义中间xml属性特殊化EditText对象属性。下面是你应该如何声明在<LinearLayout>元素中。
<EditTextandroid:id="@+id/edit_message" android:layout_width="wrap_content" android:layout_height="wrap_content" android:hint="@string/edit_message"/>
About resource objects
A resource object is simply a unique integer name that's associated with an app resource, such as a bitmap, layout file, or string.
资源对象仅仅是一个唯一整数名字,关联于app资源,比如bitmap,布局文件或字符串。
Every resource has a corresponding resource object defined in your project'sgen/R.javafile. You can use the object names in theRclass to refer to your resources, such as when you need to specify a string value for the android:hintattribute. 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.
每个资源有一个对应的资源对象,定义在工程的gen/R.java文件。你能使用对象名字在R 类中涉及你的资源,比如当你需要确定一个串值android:hint属性,你能创建专属资源ID,和view关联使用android:id属性,这个属性允许你参考视图从其他编码。
The SDK tools generate theR.javaeach time you compile your app. You should never modify this file by hand.
For more information, read the guide to Providing Resources.
sdk工具生成R.java当你每次编辑app时。你永远不用手工修改。
About these attributes:
android:idThis 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 (idin 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.javafile that refers to theEditTextelement. Once the resource ID is declared once this way, other references to the ID do not need the plus sign. Using the plus sign 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_heightInstead 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 EditTextelement would fill the screen, because it would match the size of the parent LinearLayout. For more information, see the Layouts guide. android:hintThis 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 asidorstring), so using the same name does not cause collisions.
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.
当你需要增加文本在用户界面,你总是需要特殊每个字符串做为一个资源。字符串资源允许你管理所有的ui文本在一个单独本地位置,这样很容易找到并更新文本。外在化字符串也允许你载入你的app在不同语言,通过提供不同定义在每个字符串资源。
By default, your Android project includes a string resource file atres/values/strings.xml. Open this file and delete the<string>element named"hello_world". Then add a new one named"edit_message"and set the value to "Enter a message."
默认的,android 工程包括一个字符串资源文件在res/values/strings.xml。打开这个文件删除<string>元素,此元素被命名为"hello_world". 然后增加一个新名字"edit_message",设置值为"Enter a message."。
While you’re in this file, also add a "Send" string for the button you’ll soon add, called"button_send".
但你在这个文件中,也要增加一个 “Send”字符串给你很快增加的按钮,命名为"button_send"
The result forstrings.xmllooks 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="menu_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 Devicesclass.
Add a Button
Now add a<Button>to the layout, immediately following the<EditText>element:
增加<Button>到布局,紧跟着<EditText>元素
<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:idattribute, because it won't be referenced from the activity code.
宽和高设置为"wrap_content",所以按钮只是和按钮文字一样大。按钮不需要android:id属性,因为它不会被活动code关联。
Make the Input Box Fill in the Screen Width
The layout is currently designed so that both theEditTextandButtonwidgets are only as big as necessary to fit their content, as shown in figure 2.
布局被设计,所以EditTextandButton只是按照需要的大小去适应他们的内容。
Figure 2. TheEditTextandButtonwidgets 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 aLinearLayoutwith the weight property, which you can specify using the android:layout_weight attribute.
按钮工作的很好,但是对于文本域是不好的。因为用户可能输入很多长文字,所以,适合不使用的屏幕宽给文本域要好些。你能在LinearLayout里面设置weight属性,你能特殊化它使用android:layout_weight属性。
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.
宽值是一个数字,确认每个视图消灭后保留空格个数,关联被姐妹视图消灭的数量。这有点像一个饮料配方中成分的量工程:"伏特加酒 2 个部分,1 部分咖啡甜酒"手段的三分之二的饮料是伏特加。比如,你给一个视图重为2,另外一个重为1,总和是3.所以第一个视图填充2/3的空格,另外一个填充余下的步伐。如果你增加第三个视图,给它重为1,那么第一个现在等到1/2空格,剩下的两个得到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 theEditTextelement, give it a weight of 1 and leave the button with no weight.
默认重为所有视图是0,如果你特殊话了任何的重值比0大给其中一个view,在所有视图得到要求空间之后,那么之后这个视图填充所有空间,所以,用EditText元素填充正在存在的空间在布局中,,给它一个1重,并且让按钮没有重。
<EditTextandroid:layout_weight="1" ... />
In order to improve the layout efficiency when you specify the weight, you should change the width of theEditTextto 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宽为0dp,将宽设置为0提供布局性能,应为使用"wrap_content"要求系统计算宽,这样并不相关。因为重值需要另外宽计算来适用余下的空间。
<EditText android:layout_weight="1" android:layout_width="0dp" ... />
Figure 3 shows the result when you assign all weight to theEditTextelement.
Figure 3. TheEditTextwidget is given all the layout weight, so fills the remaining space in theLinearLayout.
Here’s how your complete layout file should now look:
<?xml version="1.0" encoding="utf-8"?> <LinearLayoutxmlns:android=http://schemas.android.com/apk/res/android xmlns:tools=http://schemas.android.com/tools android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"> <EditTextandroid:id="@+id/edit_message" android:layout_weight="1" android:layout_width="0dp" android:layout_height="wrap_content" android:hint="@string/edit_message"/> <Buttonandroid:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/button_send"/> </LinearLayout>
This layout is applied by the defaultActivityclass that the SDK tools generated when you created 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 布局支持默认活动类,当你创建工程时,sdk工具生成。所以你运行app看到结果: 在eclipse,点击run。 或者在命令行,改变目录到工程根目录并且执行: 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
Starting Another Activity
- Respond to the Send Button
- Build an Intent
- Start the Second Activity
- Create the Second Activity
- Add it to the manifest
- 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 toMainActivitythat 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 themain.xmllayout file and add theandroid:onClickattribute to the<Button>element:
回应按钮的on-click 时间,打开main.xml布局文件,增加android:onClick属性给<Button>元素。
<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.
android:onClick属性的值"sendMessage",是一个活动中方法名字,当用户点击按钮时,系统调用它。
Open theMainActivityclass and add the corresponding method:
打开MainActivity类,增加对应方法
/** Called when the user clicks the Send button */ public void sendMessage(View view){ // Do something in response to button }
Tip: In Eclipse, press Ctrl + Shift + O to import missing classes (Cmd + Shift + O on Mac).
在eclipse,按下Ctrl + Shift + O来import缺失的类。
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 aViewas the only parameter (this will be theViewthat was clicked)
为了系统能匹配方法来传递方法名字给android:onClick,需要如下的特征,特殊的,方法必须:
是public
有void返回值。
有一个view座位唯一的参数。(将会view别点击)
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
AnIntentis an object that provides runtime binding between separate components (such as two activities). TheIntentrepresents 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.
Intent是一个对象,提供运行时间绑定在单独组件(比如两个活动)。INTENT 表达一个app的意图。你能用意图给很多各种各样的任务,但是更多被用来开始另外一个活动。
Inside thesendMessage()method, create anIntentto start an activity calledDisplayMessageActivity:
在sendMessage()方法中,创建一个intent来开始一个活动,这个活动被叫做DisplayMessageActivity
Intent intent =newIntent(this,DisplayMessageActivity.class);
The constructor used here takes two parameters:
- AContextas its first parameter (thisis used because theActivityclass is a subclass ofContext)
- TheClassof the app component to which the system should deliver theIntent(in this case, the activity that should be started)
构造函数用了两个参数:
Context做为第一个参数(this关键字被使用,是因为activity类是context的一个子类)
app组件类被传递给intent(在这个例子,活动需要被开始)
Sending an intent to other apps
The intent created in this lesson is what's considered an explicit intent, because theIntentspecifies the exact app component to which the intent should be given. However, intents can also be implicit, in which case theIntentdoes 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 variousIntentparameters. For more information, see the class about Interacting with Other Apps.
在这一课中创建的意图是什么考虑的明确意图,因为意图指定应给予意图的确切应用程序组件。然而,意图也可以隐式的,在这种情况下,意图不指定所需的组件,但允许来响应意图,只要它满足在各种意图参数中指定的操作的元数据规格在设备上安装的任何应用程序。
Note: The reference toDisplayMessageActivitywill 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.
如果使用IDE将会有错误,比如eclipse,应为这个类还不存在,现在先忽略这个错,你将很快创建他。
An intent not only allows you to start another activity, but it can carry a bundle of data to the activity as well. So, usefindViewById()to get theEditTextelement and add its text value to the intent:
intent不仅允许你开始一个其他活动,而且能传递一块数据给活动。所以,用findViewById()得到EditText的值,并且增加到intent中。
Intent intent =newIntent(this,DisplayMessageActivity.class); EditText editText =(EditText) findViewById(R.id.edit_message); String message = editText.getText().toString(); intent.putExtra(EXTRA_MESSAGE, message);
AnIntentcan carry a collection of various data types as key-value pairs called extras. TheputExtra()method takes the key name in the first parameter and the value in the second parameter.
intent能传递各种数据类型做为键-值对(extras)的集合.putExtra()方法传递键名字在第一个参数,键值在第二个参数。
In order for the next activity to query the extra data, you should define your key using a public constant. So add theEXTRA_MESSAGEdefinition to the top of theMainActivityclass:
为了下一个活动能查询额外数据,需要定义键用公共常量。所以增加EXTRA_MESSAGE定义在MainActivity类的顶端。
public class MainActivityextendsActivity{ 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.
通常是一个很好的练习,定义intent额外键用app包名字做前缀。这样保证是唯一的,万一应用需要和其它app交互。
Start the Second Activity
To start an activity, you simply need to callstartActivity()and pass it yourIntent. The system receives this call and starts an instance of theActivityspecified by theIntent.
为了开始活动,简单需要定义startActivity()传递意图。系统接受这样调用和开始一个活动实例,特殊化被意图。
With this new code, the completesendMessage()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 =newIntent(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 theDisplayMessageActivityclass in order for this to work.
现在需要DisplayMessageActivity类来开始工作。
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 the Android 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
- Navigation Type: None
- Hierarchial Parent: com.example.myfirstapp.MainActivity
- Title: My Message
Click Finish.
If you're using a different IDE or the command line tools, create a new file namedDisplayMessageActivity.javain the project'ssrc/directory, next to the originalMainActivity.javafile.
如果使用不同IDE或者命令行工具,创建新文件命名为DisplayMessageActivity.java在工程src/目录下,接下来起源于MainActivity.java。
Open theDisplayMessageActivity.javafile. If you used Eclipse to create it, the class already includes an implementation of the requiredonCreate()method. There's also an implementation of theonCreateOptionsMenu()method, but you won't need it for this app so you can remove it. The class should look like this:
打开DisplayMessageActivity.java文件,如果你用eclipse创建,类已经包含需要实现的onCreate()方法。也有实现onCreateOptionsMenu()方法,但你不需要在这个app,所以你可以删除它。
public class DisplayMessageActivity extends Activity{ @Override publicvoid onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_display_message); } }
All subclasses ofActivitymust implement theonCreate()method. The system calls this when creating a new instance of the activity. It is where you must define the activity layout and where you should perform initial setup for the activity components.
所有activity子类需要实现onCreate()方法。系统命名为创建新的活动实例。 存在你必须定义活动布局的地方,操作初始化步骤为所有的活动组件地方。
Add it to the manifest
You must declare all activities in your manifest file,AndroidManifest.xml, using an<activity> element.
你需要声明所有的活动在清单文件AndroidManifest.xml,使用<activity>元素。
When you use the Eclipse tools to create the activity, it creates a default entry. It should look like this:
当使用eclipse工具创建活动,是默认创建的。
<application ... > ... <activity android:name=".DisplayMessageActivity" android:label="@string/title_activity_display_message"> <meta-data android:name="android.support.PARENT_ACTIVITY" android:value="com.example.myfirstapp.MainActivity"/> </activity> </application>
The <meta-data> element declares the name of this activity's parent activity within the app's logical hierarchy. The Android Support Library uses this information to implement default navigation behaviors, such as Up navigation.
<meta-data>元素什么了父活动的名字在app逻辑等级中。androidSupport Library用这个信息实现默认航海行为比如向上航海。
Note: During installation, you should have downloaded the latest Support Library. Eclipse automatically includes this library in your app project (you can see the library's JAR file listed under Android Dependencies). If you're not using Eclipse, you may need to manually add the library to your project—follow this guide for setting up the Support Library.
The app is now runnable because theIntentin the first activity now resolves to theDisplayMessageActivityclass. If you run the app now, clicking the Send button starts the second activity, but it's still using the default "Hello world" layout.
Receive the Intent
EveryActivityis invoked by anIntent, regardless of how the user navigated there. You can get theIntentthat started your activity by callinggetIntent()and retrieve the data contained within it.
每个互动被intent调用,不考虑用户如何导航。你能得到intent,开始你的活动用getIntent(),接受包含在里面的数据。
In theDisplayMessageActivityclass’sonCreate()method, get the intent and extract the message delivered by
在DisplayMessageActivity类的onCreate()方法中,得到意图和额外信息从MainActivity:传递而来。
MainActivity:
Intent intent = getIntent(); String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
Display the Message
To show the message on the screen, create aTextViewwidget and set the text usingsetText(). Then add theTextViewas the root view of the activity’s layout by passing it tosetContentView().
为了显示屏幕信息,创建textview部件,用setText()设置文本内容。增加TextView做为布局根视图,用setContentView().传递textview。
The completeonCreate()method forDisplayMessageActivitynow looks like this:
@Overridepublicvoid 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 =newTextView(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.
Figure 2. Both activities in the final app, running on Android 4.0.
That's it, you've built your first Android app!
To learn more about building Android apps, continue to follow the basic training classes. The next class is Managing the Activity Lifecycle.
another activity, and more.