Starting Another Activity

开启另一个Activity

This lesson teaches you to

这节课教给你:

  1. Respond to the Send Button

    给发送按钮设置响应

  2. Build an Intent

    创建一个意图
  3. Start the Second Activity

    开启第二个Activity
  4. Create the Second Activity

    创建第二个Activity
  5. Receive the Intent

    接受意图
  6. Display the Message

    显示消息

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.

在完成前一个课程后,你现在拥有这样一个app:它会展现一个包含一个文本域和一个按钮的activity(一屏)。在这节课中,你讲在MainActivity中添加一些代码:当用户点击发送按钮的时候会开启一个新的activity。

Respond to the Send Button

给发送按钮设置响应

To respond to the button’s on-click event, open the fragment_main.xml layout file and add the android:onClick attribute to the element:

想要给按钮添加点击事件,请打开fragment_main.xml布局文件然后给< Button>元素添加一个android:onClick属性。

<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”是当用户点击按钮时系统会在你的activity中回调的一个方法的名字。

Open the MainActivity class (located in the project’s src/ directory) and add the corresponding method:

打开MainActivity类(位于项目的 src/目录下),然后添加相应的方法:

/** 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:

为了让系统能把这个方法和你刚刚给android:onClick设置的方法匹配,名字必须正确的给出。特别地,这个方法必须:

  • Be public

    是共有的

  • Have a void return value

    有一个空的返回值

  • Have a View as the only parameter (this will be the View that was clicked)

    有一个并且只有一个View参数(这就是被点击后触发的那个View)

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

接下来,你将把这个方法的内容填充完整:读取文本域中的内容然后发送这些内容到另一个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.

意图是在各个独立组件之间提供运行时绑定的一个对象(比如两个activity)。意图代表一个app“想要做某事”。你可以在各种各样的任务中使用意图,但是,它们通常被使用在开启另一个activity。

Inside the sendMessage() method, create an Intent to start an activity called DisplayMessageActivity:

在sendMessage()方法里,创建一个意图来开启一个名叫DisplayMessageActivity的activity:

Intent intent = new Intent(this, DisplayMessageActivity.class);

This requires that you import the Intent class:

这需要你引入一个Intent类:

import android.content.Intent;

Tip: In Eclipse, press Ctrl + Shift + O to import missing classes (Cmd + Shift + O on Mac).

小技巧:在Eclipse中,按住Ctrl + Shift + O键可以导入缺少的类(在Mac中是Cmd + Shift + O)。

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)

    第一个参数是一个上下文(在这里使用是因为Activity类是上下文的一个子类)

  • The Class of the app component to which the system should deliver the Intent (in this case, the activity that should be started)

    系统应该传递什么意图到应用程序的组件的哪个类中(在这个实例中,是让activity开启)

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.

在这节课中创建的这个意图是一个明确的意图,因为这个意图确切地指定了它应该传递给应用程序的哪个组件。然而,意图也可能是不确切地,在这种情况下,意图不能够指定所需的组件,但是它允许在设备上安装的任何应用程序去响应这个意图,只要这个应用程序在action(动作)中指定相应的meta-data(元数据)规范,action中可以用来指定不同的意图参数。

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.

注意:如果你使用诸如Eclipse这样的集成开发环境,对DisplayMessageActivity的引用将会引起一个错误,因为这个类现在还不存在。现在请忽视这个错误;等下你将会创建它。

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:

意图不仅允许你开启另一个activity,它还可以让你携带一捆数据到另一个activity中。在sendMessage()方法中,使用findviewById()得到文本框元素,然后在意图中拿到它的文本值:

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 for android.widget.EditText. You’ll define the EXTRA_MESSAGE constant in a moment.

注意:你现在需要导入一个android.widget.EditText的声明清单。等下,你将定义EXTRA_MESSAGE这个常量。

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.

意图对象能携带一些不同类型的数据,这种数据是一些被叫做extras(附加部分)的键值对。putExtras()方法的第一个参数接受一个key(键)名字,第二个参数接受一个value(值)。

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:

为了能让下一个activity查询到该extra数据,你应该使用一个公共常量在你的意图的extra中定义一个键。因此在MainActivity类的上面增加一个EXTRA_MESSAGE的定义:

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.

使用你的应用程序的包名作为意图的extra的定义的前缀,这通常是一个好的做法。万一你的应用程序要和其他的应用程序发生作用,这可以保证他们是独一无二的。

Start the Second Activity

开启第二个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.

为了开启一个activity,调用startActivity()并将其传递给你的意图对象。系统会接收这个调用,通过意图对象来开启一个指定的Activity实例。

With this new code, the complete sendMessage() method that’s invoked by the Send button now looks like this:

加上这些新代码后,发送按钮调用的sendMessage()方法现在看起来应该如下:

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

为了让其进行工作,现在你需要创建一个DisplayMessageActivity类。

Create the Second Activity

创建第二个Activity

![adt-new-activity.png](http://7xogui.com1.z0.glb.clouddn.com/adt-new-activity.png)

Figure 1. The new activity wizard in Eclipse.

图1 在Eclipse创建新的activity向导

To create a new activity using Eclipse:

为了使用Eclipse创建一个新的activity

  1. Click New in the toolbar.

    在工具栏中点击New。

  2. In the window that appears, open the Android folder and select Android Activity. Click Next.

    在出现的窗口中,打开Android文件然后选择Android Activity。点击Next。
  3. Select BlankActivity and click Next.

    选择BlankActivity然后点击Next。
  4. Fill in the activity details:

    把activity详情中填满:

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

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

如果你使用不同的集成开发环境或者命令行工具,请在项目的 src/ 目录下创建一个新的名叫DisplayMessageActivity.java的文件,它应该紧挨着原来的MainActivity.java文件。

Open the DisplayMessageActivity.java file. If you used Eclipse to create this activity:

打开DisplayMessageActivity.java文件。如果你使用Eclipse创建的这个activity:

  • The class already includes an implementation of the required onCreate() method. You will update the implementation of this method later.

    这个类早已经包含了一个需要实现的onCreate()方法。你等下需要更新实现这个方法。

  • There’s also an implementation of the onCreateOptionsMenu() method, but you won’t need it for this app so you can remove it.

    这儿还有一个需要实现的onCreateOptionsMenu()方法,但是对于这个应用程序你不需要它,因此把它移除即可。

  • There’s also an implementation of onOptionsItemSelected() which handles the behavior for the action bar’s Up behavior. Keep this one the way it is.

    这儿还有一个需要实现的onOptionsItemSelected()方法,它是用来处理action bar(工具栏)顶部的项目的行为的。让它保持这样就行。

  • There’s also a PlaceholderFragment class that extends Fragment. You will not need this class in the final version of this activity.

    这儿还有一个继承了Fragment的PlaceholderFragment类。在这个类的最后版本中你也不需要它。

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.

Fragments(碎片)把应用程序的功能和UI分解成可重用模块。请看Fragments API Guide获取更多关于fragments的信息。这个activity的最终版本是不需要使用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.

注意:如果你使用的不是最新版本的ADT插件,你的activity可能看起来和这不一样。为了完成本教程请确保你安装了最新版本的ADT插件。(其实并不需要,你只要创建好一个activity即可----译者注)

The DisplayMessageActivity class should now look like this:

>DisplayMessageActivity类应该是这个样子:

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.

如果你使用除了Eclipse之外其它的集成开发环境,请使用上面的代码去更新你的DisplayMessageActivity类。

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.

所有Activity的子类都必须实现onCreate()方法。当系统创建一个新的activity实例时会调用它。在这个方法中,你必须使用setContentView()方法定义activity的布局,并且你需要对activity的组件进行初始化设置。

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.

注意:如果你使用除了Eclipse之外其它的继承开发环境,你的项目不包含setContentView()需要的activity_display_message布局。这没什么事儿,因为等下你将更新这个方法,并且不会使用这个布局。

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.

如果你使用Eclipse,你可以跳过这节,因为模板对于新的activity提供了标题文本。

If you’re using an IDE other than Eclipse, add the new activity’s title to the strings.xml file:

如果你不使用Eclipse,请在strings.xml文件中增加新的activity的标题:

<resources>
...
<string name="title_activity_display_message">My Message</string>
</resources>

Add it to the manifest

添加到manifest(清单)中

All activities must be declared in your manifest file, AndroidManifest.xml, using an element.

所有的activities必须在你的manifest文件的AndroidManifest.xml中明确声明,通过使用一个元素。

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:

当你使用Eclipse工具栏创建一个activity时,它创建了一个默认的入口。如果你使用不同的集成开发环境,你需要自己添加一个manifest入口。它应该是这个样子:

<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 navigation on 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 element as shown here.

android:parentActivityName这个属性声明了在应用逻辑层结构这个activity的父activity。系统使用这个值去实现默认的导航行为,比如在Android 4.1(API 16)或者更高版本的Android上最上面的导航。对于Android旧版本你可以通过使用支持类库并且添加元素来让其提供相同的导航行为,就像这儿显示的一样。

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.

注意:你的Android SDK应该早已经引入了最新的Android支持类库。它在ADT(Android开发工具)包中,如果你使用不同的集成开发环境,在Adding Platforms and Packages那步你也应该安装过了。在Eclipse中使用模板会自动把支持类库添加到你的app项目中(你可以在Android Dependencies下看见支持类库的JAR文件)。如果你不适用Eclipse,你需要在你的项目中手动添加支持类库—–请跟着setting up the Support Library向导完成,然后回到这里。(一般都用Eclipse,这个向导的具体位置也不用说了—–译者注)

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.

如果你使用Eclipse进行开发,你现在可以运行你的应用程序了,但是相比之前并不会有什么不同发生。点击发送按钮会开启第二个activity,但是它使用的是模板提供的一个默认的“Hello world”布局。不久,你将使用一个自定义文本来代替这个activity中的布局,因此如果你使用不同的继承开发环境,请不用担心这个应用程序还不能编译。

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.

不管用户怎么导航,每个Activity都要通过一个意图来调用。你可以在开启的activity中通过调用getIntent()来得到意图,并且取出其中包含的数据。

In the DisplayMessageActivity class’s onCreate() method, get the intent and extract the message delivered by MainActivity:

在DisplayMessageActivity类中的onCreate()方法中,拿到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 setText(). Then add the TextView as the root view of the activity’s layout by passing it to setContentView().

为了在屏幕上展现消息,请创建一个文本组件,然后使用setText()来给它设置文本。然后在这个activity的布局中通过使用setContentView()把这个文本组价添加到根布局上。

The complete onCreate() method for DisplayMessageActivity now looks like this:

完成onCreate()方法后的DisplayMessageActivity看起来是如下这个样子:

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

现在你可以运行你的应用程序了。当你打开的时候,在文本域中输入一个消息,点击发送,然后消息会出现在第二个activity中。

Figure 2. Both activities in the final app, running on Android 4.4.

图2 运行在Android 4.4上的最终的应用程序的所有activities

That’s it, you’ve built your first Android app!

这就是所有了,你已经创建了你的第一个Android应用程序!

To learn more, follow the link below to the next class.

想学习更多,跟着下面的链接进入下一节课吧。

Next class: Adding the Action Bar

下一课:增加一个Action Bar(指令工具栏)

这个是我自己翻译的,如果您发现其中有重要错误,敬请指出!

Android官方文档翻译 六 1.4Starting Another Activity的更多相关文章

  1. Android官方文档翻译 十七 4.1Starting an Activity

    Starting an Activity 开启一个Activity This lesson teaches you to 这节课教给你 Understand the Lifecycle Callbac ...

  2. android官方文档翻译(不断更新中。。。)

    最近在自学android,抽空把官方文档的guide跟training差不多看了一遍,又对比了一些书籍,感觉还是官方文档讲得比较好,所以自己计划把官方文档翻译一下,方便自己的知识巩固以及复习查找,由于 ...

  3. Android官方文档翻译 九 2.2Adding Action Buttons

    Adding Action Buttons 增加动作按钮 This lesson teaches you to 这节课教给你 Specify the Actions in XML 在XML中指定动作 ...

  4. Android官方文档翻译 十五 3.3Supporting Different Platform Versions

    Supporting Different Platform Versions 支持不同的平台版本 This lesson teaches you to 这节课教给你 Specify Minimum a ...

  5. Android官方文档翻译 十 2.3Styling the Action Bar

    Styling the Action Bar 设计菜单栏的样式 This lesson teaches you to 这节课教给你 Use an Android Theme 使用一个Android主题 ...

  6. Android官方文档翻译 十六 4.Managing the Activity Lifecycle

    Managing the Activity Lifecycle 管理activity的生命周期 Dependencies and prerequisites 依赖关系和先决条件 How to crea ...

  7. Android官方文档翻译 十八 4.2Pausing and Resuming an Activity

    Pausing and Resuming an Activity 暂停和恢复一个activity This lesson teaches you to 这节课教给你 Pause Your Activi ...

  8. Android官方文档翻译 四 1.2Running Your App

    Running Your App If you followed the previous lesson to create an Android project, it includes a def ...

  9. Android官方文档翻译 三 1.1Creating an Android Project

    Creating an Android Project 创建一个Android项目 An Android project contains all the files that comprise th ...

随机推荐

  1. ☕【Java深层系列】「技术盲区」让我们一起去挑战一下如何读取一个较大或者超大的文件数据!

    Java的文件IO流处理方式 Java MappedByteBuffer & FileChannel & RandomAccessFile & FileXXXputStream ...

  2. 使用批处理文件(.bat)启动多个CMD窗口并执行命令

    由于每次启动本机的kafka都需要打开2个cmd窗口,分别启动zookeeper服务和kafka服务,操作相对繁琐,于是想起了批处理来帮忙一键启动. 在桌面新建一个txt文件,改后缀名为.bat,并加 ...

  3. CF475A Bayan Bus 题解

    Update \(\texttt{2020.10.6}\) 修改了一些笔误. Content 模拟一个核载 \(34\) 人的巴士上有 \(k\) 个人时的巴士的状态. 每个人都会优先选择有空位的最后 ...

  4. DNS解析超时排查/etc/resolv.conf single-request-reopen参数说明

    添加 options rotate timeout:1 attempts:3 single-request-reopen 添加到/etc/resolv.conf 中 #释义: 循环查询 超时时间 重试 ...

  5. 【LeetCode】84. Largest Rectangle in Histogram 柱状图中最大的矩形(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 单调栈 日期 题目地址: https://leetc ...

  6. 【LeetCode】594. Longest Harmonious Subsequence 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 统计次数 日期 题目地址:https://leetc ...

  7. Code(hdu5212)

    Code Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)Total Submis ...

  8. Spring Boot实战三:集成RabbitMQ,实现消息确认

    Spring Boot集成RabbitMQ相比于Spring集成RabbitMQ简单很多,有兴趣了解Spring集成RabbitMQ的同学可以看我之前的<RabbitMQ学习笔记>系列的博 ...

  9. Geometric GAN

    目录 概 主要内容 McGAN 结合SVM 训练 训练 理论分析 证明 Jae Hyun Lim, Jong Chul Ye, Geometric GAN. 概 很有趣, GAN的训练过程可以分成 寻 ...

  10. [opencv]<学习Opencv>英文原版翻译学习

    [注]下文全部内容为 <<Learning OpenCV 3: Computer Vision in C++ with the OpenCV Library>>经由在线翻译整理 ...