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.

更多学习,请看下一节。

更多相关文章

  1. 浅谈Java中Collections.sort对List排序的两种方法
  2. 箭头函数的基础使用
  3. NPM 和webpack 的基础使用
  4. Python list sort方法的具体使用
  5. 【阿里云镜像】使用阿里巴巴DNS镜像源——DNS配置教程
  6. python list.sort()根据多个关键字排序的方法实现
  7. android上一些方法的区别和用法的注意事项
  8. android 使用html5作布局文件: webview跟javascript交互
  9. android实现字体闪烁动画的方法

随机推荐

  1. Android---把数据保存到数据库中(一)
  2. 【6.21】PreferenceActivity来设置settin
  3. android 热更新之腾讯Bugly 及所遇问题的
  4. Android非常简单的TextView展开和收起,在
  5. Android---线程间通讯
  6. [置顶] 【Android】 给我一个Path,还你一
  7. Android中运行OpenGL工程出错:java.lang.I
  8. 目前可用的Android(安卓)SDK在线更新镜像
  9. Android四种加载方式
  10. Android(安卓)NDK学习笔记