`
大碗干拌
  • 浏览: 46050 次
  • 性别: Icon_minigender_1
  • 来自: 西安
文章分类
社区版块
存档分类
最新评论

Android官方教程翻译(4)——启动另一个Activity

 
阅读更多

Starting Another Activity

启动另一个Activity

PREVIOUSNEXT

THIS LESSON TEACHES YOU TO

这节课教你

1.Respond to the Send Button按钮响应

2.Build an Intent创建一个意图Intent

3.Start the Second Activity开启第二个activity

4.Create the Second Activity创建第二个activity

5.Receive the Intent接收Intent

6.Display the Message显示消息

YOU SHOULD ALSO READ

·Installing the SDK

After completing theprevious lesson, youhave an app that shows an activity (a single screen) with a text field and abutton. In this lesson, you’ll add some code toMainActivitythat starts a new activity when the user clicks the Sendbutton.

完成前面的课程后,你应该有一个包含文本域和一个按钮的应用。在这节课中,将添加一些代码来实现当用户点击按钮后启动新的activity

Respond to the Send Button

按钮的响应


To respond to the button's on-click event, open theactivity_main.xmllayout file and add theandroid:onClickattributeto the<Button>element:

为了响应按钮的点击事件,打开activity_main.xml布局文件给按钮添加androidonClick属性。

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_send"
android:onClick="sendMessage"/>

Theandroid:onClickattribute’s value,"sendMessage", is the name of a method in your activity that the systemcalls when the user clicks the button.

Anroid:onClick属性的值”sendMessage”就是对应anctivity中监听方法的名字。

Open theMainActivityclass (located in the project'ssrc/directory) and add the corresponding method:

打开MainActivity(在工程文件的src/目录下)添加响应方法。

/** Called when the user clicks theSend button */
public void sendMessage(View view){
// Do something in response to button
}

This requires that you import theViewclass:

这里要导入View类的jar

import android.view.View;

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

提示:在Eclipse中按Ctrl+Shift+O可以自动导包

In order for the system to match this method to the methodname given toandroid:onClick,the signature must be exactly as shown. Specifically, the method must:

为了让该方法能匹配到androidonClick属性的值,这里必须具体说明该方法:

·Bepublic公有的

·Havea void return value空返回值

·HaveaViewas the only parameter (this will be theViewthat was clicked)

唯一一个View参数(View是被点击的视图对象)

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

下来,可以重写该方法去读文本域中输入的内容,并将该内容发送给另外一个activity

Build an Intent

创建意图


AnIntentis an object that provides runtime binding between separatecomponents (such as two activities). TheIntentrepresents an app’s "intent to do something." Youcan use intents for a wide variety of tasks, but most often they’re used tostart another activity.

Intent是一个绑定在两个组件(例如两个activity)之间的对象,这个Intent表示应用程序“有意向去做一些事”。你可以使用Intent来完成比较复杂的任务,但是更多的时候是用来启动另外一个activity

Inside thesendMessage()method, create anIntentto start an activity calledDisplayMessageActivity:

sendMessage()方法中,创建一个Intent去启动一个叫DisplayMessageActivityactivity

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

The constructor used here takes two parameters:

该对象的构造函数接受两个参数。

·AContextas its first parameter (thisis used because theActivityclass is a subclass ofContext)

上下文Context是第一个参数(使用该参数的是因为Activity继承自Context是的的textyageActivity内容,一些代码来实现启东新)

·TheClassof the app component to which the system should deliver theIntent(in this case, the activity that should be started)

系统组件类应该发送这个Intent给另外一个activity(如本例中activity被启动)

Sending an intent to other apps

发送一个意图到其他应用

The intent created in this lesson is what's considered anexplicit intent, because theIntentspecifies the exact app component to which the intent shouldbe given. However, intents can also beimplicit, in which case theIntentdoes not specify the desired component, but allows any appinstalled on the device to respond to the intent as long as it satisfies themeta-data specifications for the action that's specified in variousIntentparameters. For more information, see the class aboutInteracting with Other Apps.

课程中创建的是一个显式的意图,因为已经明确了它将启动那个组件,然而Intent也有隐式的意图,这种意图没有明确指定要启动哪个组件,应用会根据Intent指定的规则去启动符合条件的组件,具体是哪个组件则不确定。有关更多的信息,请参看Interacting with Other Apps.

Note:The reference toDisplayMessageActivitywill raise an error if you’re using an IDE such as Eclipsebecause the class doesn’t exist yet. Ignore the error for now; you’ll createthe class soon.

An intent not only allows you to start another activity, butit can carry a bundle of data to the activity as well. Inside thesendMessage()method, usefindViewById()to get theEditTextelement and add its text value to the intent:

注意:如果你使用的是像Eclipse的集成环境,引用DisplayMessageActivity将产生一个错误。因为这个类没有被创建。先忽略这个错误,你马上将创建一个类。

Intent intent = new Intent(this,DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);

Note:You now need import statements forandroid.content.Intentandandroid.widget.EditText. You'll define theEXTRA_MESSAGEconstant in a moment.

注意:你现在需要导入android.content.Intentandroid.widget.EditText.两个包和定义EXTRA_MESSAGE常量。

AnIntentcan carry a collection of various data types as key-valuepairs calledextras. TheputExtra()method takes the key name in the first parameter and thevalue in the second parameter.

意图可以携带各种数据类型的键值对,putExtra()方法第一个参数是键,第二个参数是值。

In order for the next activity to query the extra data, youshould define the key for your intent's extra using a public constant. So addtheEXTRA_MESSAGEdefinition to the top of theMainActivityclass:

为了让下面的activity去获取该数据,你应该定义一个常量并赋值。所以在MainActivity的上面去定义EXTRA_MESSAGE.

public class MainActivity extends Activity {
public finalstatic String EXTRA_MESSAGE= "com.example.myfirstapp.MESSAGE";
...
}

It's generally a good practice to define keys for intentextras 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

开启第二个Activity


To start an activity, callstartActivity()and pass it yourIntent. The system receives this call and starts an instance of theActivityspecified by theIntent.

开启activity的方法叫startActivity()要将Intent传递给新activity。系统接受到该响应并开启一个指定Intentactivity实例。

With this new code, the completesendMessage()method that's invoked by the Send button now looks like this:

在新代码中,sendMessage()方法被第二个按钮调用,代码如下:

/** Called when the user clicks theSend 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 theDisplayMessageActivityclass in order for this to work.

现在来创建DisplayMessageActivity

Create the Second Activity

创建第二个Activity



Figure 1.The new activity wizard in Eclipse.

To create a new activity using Eclipse:

1.ClickNewin the toolbar.

2.Inthe window that appears, open theAndroidfolderand selectAndroidActivity. ClickNext.

3.SelectBlankActivityand clickNext.

4.Fillin the activity details:

o Project: MyFirstApp

o Activity Name: DisplayMessageActivity

o Layout Name: activity_display_message

o Title: My Message

o Hierarchial Parent: com.example.myfirstapp.MainActivity

o Navigation Type: None

ClickFinish.

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.

//和创建第一个activity的方法一样

Open theDisplayMessageActivity.javafile. If you used Eclipse to create this activity:

如果你使用Eclipse来创建这个activity,请打开DispalyMessageActivity.java

·Theclass already includes an implementation of the requiredonCreate()method.

该类已经包含了一个onCreate()的实现方法

·There'salso an implementation of theonCreateOptionsMenu()method, but you won't need it for this app so you can removeit.

还有一个onCreateOptionMenu()实现方法,这个方法不需要可以删掉。

·There'salso an implementation ofonOptionsItemSelected()which handles the behavior for the action bar'sUpbehavior. Keep this one the way it is.

还有一个onOptionsItemSelected()监听动作行为的方法,不要改动。

Because theActionBarAPIs are available only onHONEYCOMB(API level 11) and higher, you must add a condition aroundthegetActionBar()method to check the current platform version. Additionally,you must add the@SuppressLint("NewApi")tag to theonCreate()method to avoidlinterrors.

因为ActionBar只在API11以后有,你必须添加一个getActionBar()方法去检测当前平台版本。另外,

你还应该给onCreate()方法添加@SuppressLint("NewApi")标签来去掉提示。

Lint是一个静态检查器,它围绕Android项目的正确性、安全性、性能、可用性以及可访问性进行分析。它检查的对象包括XML资源、位图、ProGuard配置文件、源文件甚至编译后的字节码。

这一版本的Lint包含了API版本检查、性能检查以及其他诸多特性。其中还有一个重要的改动是Lint可以使用@SuppressLint标注忽略指定的警告。

这个是android带的lint工具提示的,lint官方的说法是Improving Your Code with lint,应该是帮助提升代码的,如果不想用的话,可以右键点工程,然后在android tools中,选择clear lint marker就没有这个错误了

TheDisplayMessageActivityclass should now look like this:

DisplayMessageActivity类如下:

public class DisplayMessageActivity extends Activity {

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

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

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

If you used an IDE other than Eclipse, update yourDisplayMessageActivityclass with the above code.

如果你使用的是其他集成开发环境,更改代码如上。

All subclasses ofActivitymust implement theonCreate()method. The system calls this when creating a new instance ofthe activity. This method is where you must define the activity layout with thesetContentView()method and is where you should perform initial setup for theactivity components.

所有的Activity子类都必须实现onCreate()方法。当创建新实例时系统会调用该方法。在该方法中你必须用setContentView()定义你要初始化显示的xml布局文件。

Note:If you are using an IDE other than Eclipse, your project doesnot contain theactivity_display_messagelayout that's requested bysetContentView(). That's OK because you will update this method later andwon't be using that layout.

注意:如果你使用的是其他的集成开发环境,你的工程中setContentView中定义的是activity_display_message布局文件,但你不想使用该布局文件,没关系,因为你即将更改该布局文件。

Add the title string

添加标题字符

If you used Eclipse, you can skip to thenext section,because the template provides the title string for the new activity.

如果你使用Eclipse,你可以跳过。

If you're using an IDE other than Eclipse, add the newactivity's title to thestrings.xmlfile:

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

Add it to the manifest

mainfest文件添加配置

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

所有的activity都必须在mainfest文件中使用<activity>声明。

When you use the Eclipse tools to create the activity, itcreates a default entry. If you're using a different IDE, you need to add themanifest entry yourself. It should look like this:

Eclipse创建activity时,默认创建。用其他开发环境,你需要去手动添加。如下:

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

Theandroid:parentActivityNameattribute declares the name of this activity's parentactivity within the app's logical hierarchy. The system uses this value toimplement default navigation behaviors, such asUp navigationonAndroid 4.1 (API level 16) and higher. You can provide the same navigationbehaviors for older versions of Android by using theSupport Libraryand adding the<meta-data>element as shown here.

Android:parentActivityName属性声明了该activity的父类activity的路径,系统使用该配置寻找。

Note:Your Android SDK should already include the latest AndroidSupport Library. It's included with the ADT Bundle but if you're using adifferent IDE, you should have installed it during theAdding Platforms and Packagesstep. When using the templates in Eclipse, the SupportLibrary is automatically added to your app project (you can see the library'sJAR file listed underAndroidDependencies). If you're notusing Eclipse, you need to manually add the library to your project—follow theguide forsetting up the Support Librarythen 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 butit uses a default "Hello world" layout provided by the template.You'll soon update the activity to instead display a custom text view, so ifyou're using a different IDE, don't worry that the app won't yet compile.

如果你使用的是Eclipse,你现在可以运行该应用了,但是没有什么特别的事发生,点击第二个按钮去启动activity,但是还是默认的“Helloword”.

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.

每个Activity是被Intent调用的,无论用户如何跳转,你可以通过getIntent()得到Intnet实例并取出里面的数据。

In theDisplayMessageActivityclass’sonCreate()method, get the intent and extract the message delivered byMainActivity:

DisplayMessageActivity类的onCreate()方法中,可以获取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().

为了在屏幕上显示消息,创建一个文本域部件并使用setText()设置文本,然后将该部件作为根视图给setContentView()方法。

The completeonCreate()method forDisplayMessageActivitynow looks like this:

现在DisplayMessageActivity类的onCreate()方法如下:

@Override
public void onCreate(BundlesavedInstanceState){
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 activitylayout
setContentView(textView);
}

You can now run the app. When it opens, type a message in thetext field, click Send, and the message appears on the second activity.

你可以运行该例子,打开程序,输入一段文字,点击按钮,看到将该字符串发送到了第二个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 followthe basic training classes. The next class isManaging the Activity Lifecycle.

更多学习,请看下一节。

分享到:
评论

相关推荐

    Android开发笔记——模拟器、应用教程

    Android开发笔记,内容涉及模拟器参数、进程与线程、Android 释放手机资源,进程释放优先级、分析HelloAndroid、添加编辑框与按钮、使用Intent启动另一个Activity、在不同Task中启动Activity、Intent与Intent ...

    Android实验二:Activity的生命周期及Intent

    1、设计界面,包括四个按钮,两个文本框。单击对应按钮可以启动对应...假定Activity A为启动Activity。 2、修改 Activity 的启动模式 LaunchMode,并通过 Log 信息来体会不同启动模式所对应的Activity 和 task 的关系

    android开发——简易计算器的设计报告.doc

    (此时前台启动了另一个活动);void onStop()不需要某个活动了,就调用;void onDestroy()销毁活动。 (2)多个Activity之间的跳转:通过Intent类实现屏幕之间的跳转(包括没有参数关系 和需要传递参数两种情况)。...

    新版Android开发教程.rar

    Android 是一个专门针对移动设备的软件集,它包括一个操作系统,中间件和一些重要的应用程序。 Beta 版 的 Android SDK 提供了在 Android 平台上使用 JaVa 语言进行 Android 应用开发必须的工具和 API 接口。 特性 ...

    Android开发与应用——张荣,原书配套课件

    5.3.3 获取另一个界面返回结果 5.4 小结 练习 第6章 Android数据存储与共享 6.1 数据存储与共享方式概述 6.2 首选项信息 6.2.1 私有数据存储 6.2.2 公有数据存储与共享 6.3 数据文件 6.3.1 内存...

    android开发入门教程

    9.1.2 用Intent启动一个新的Activity 9.1.3 Intent详细讲解 9.1.4 Android解析Intent实现 9.2 用广播告诉你——利用Intent来广播(BroadCast)事件 9.2.1 实现Android中的广播事件 9.2.2 BroadCastReceiver介绍 9.3 ...

    [图解]Android源码分析——Activity的启动过程

    Activity的启动过程一.Launcher进程请求AMSLauncher.java的startActivitySafely方法的执行过程:Activity.java中startActivity方法的执行过程:startActivityForResult方法的执行过程:Instrumentation.java中...

    Android应用开发详解

    Android 应用案例——备忘录,通过一个Android基础应用项目综合应用了Android中的各种组件,包括Activity、Service、Broadcast Receiver、ContentProvider、Intent和View的应用 第18章 Android应用案例——无线点餐...

    android开发资料大全

    Android数据库最基础的一个例子(本人已测试,可以运行) 为launcher添加一个仿Mac的dock(附源码) 使用Gallery实现Tab 仿QQ--tab切换动画实例 Android 小项目之---猜扑克牌游戏 (附源码) fleep滑动切换tab(切换...

    android开发入门与实战(下)

    9.1.2 用Intent启动一个新的Activity 9.1.3 Intent详细讲解 9.1.4 Android解析Intent实现 9.2 用广播告诉你——利用Intent来广播(BroadCast)事件 9.2.1 实现Android中的广播事件 9.2.2 BroadCastReceiver介绍 9.3 ...

    《Google Android开发入门与实战》.pdf

    9.1.2 用intent启动一个新的activity 174 9.1.3 intent 详细讲解 177 9.1.4 android解析intent实现 179 9.2 用广播告诉你——利用intent来广播(broadcast)事件 180 9.2.1 实现android中的广播事件 180...

    Android编程入门很简单.(清华出版.王勇).part1

    第3章创建第一个程序——helloworld 3.1新建第一个程序 3.1.1新建工程 3.1.2运行程序 3.2认识HelloWodd 3.2.1 首识Android工程 3.2.2认识布局文件 3.2.3认识值文件 3.2.4认识R文件 3.2.5认识注册文件 3.3调试程序 ...

    Android开发笔记(三)——创建第一个Android项目

    创建 第一个Android 工程 1)启动 Eclipse,菜单栏选择 File -&gt; New -&gt; Project…。 2)在 New Project 窗口的列表中找到 Android,选择 Android Application Project。 3)输入前三项项目信息,之后选项保持默认...

    android开发入门与实战(上)

    9.1.2 用Intent启动一个新的Activity 9.1.3 Intent详细讲解 9.1.4 Android解析Intent实现 9.2 用广播告诉你——利用Intent来广播(BroadCast)事件 9.2.1 实现Android中的广播事件 9.2.2 BroadCastReceiver介绍 9.3 ...

    Android跨应用启动实例详解

    Android跨应用启动 前言: 相信大家,很多时候都...第一种:在Activity中,启动另一个app的组件。 第二种:在Service中,启动另一个app的组件。 从所周知,Android中有四大组件,那么为什么小编,只介绍Activity和Se

    Android基础——Activity基础

    应用内Activity的跳转方式 ...这是启动的Activity package com.example.myapplication.intentinner; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.

    Google.Android开发入门与实战

    9.1.2 用Intent启动一个新的Activity 9.1.3 Intent详细讲解 9.1.4 Android解析Intent实现 9.2 用广播告诉你——利用Intent来广播(BroadCast)事件 9.2.1 实现Android中的广播事件 9.2.2 BroadCastReceiver介绍 9.3 ...

    Android开发指南中文版-----应用程序框架

    查询一个内容提供器Querying a Content Provider 57 修改数据Modifying Data 61 创建一个内容提供器Creating a Content Provider 64 Content URI 总结 67 清单文件The AndroidManifest.xml File 68 清单文件结构...

    Android项目开发范例大全 9787113147945

    1.2.1创建第一个Android项目 1.2.2AndroidManifest文件 1.2.3资源文件夹 1.2.4R.java 1.2.5程序的实现原理 1.2.6Activity生命周期 1.3Android基本控件 …… 第2章“天天向上”——桌面小插件与数据库存储的学习 第3...

Global site tag (gtag.js) - Google Analytics