首页 > 代码库 > Android官方入门文档[4]启动另一个Activity

Android官方入门文档[4]启动另一个Activity

Android官方入门文档[4]启动另一个Activity

 

Starting Another Activity
启动另一个Activity

This lesson teaches you to
1.Respond to the Send Button
2.Build an Intent
 3.Create the Second Activity
4.Receive the Intent
5.Display the Message

You should also read
?Installing the SDK

这节课教你
1.响应发送按钮
2.建立一个Intent
3.创建第二个Activity
4.接收的意图
5.显示消息

你也应该阅读
?安装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 to MyActivity that starts a new activity when the user clicks the Send button.
在完成上一课后,你有一个应用程序,展示Activity(单屏)与文本字段和一个按钮。在本课程中,您将添加一些代码来MyActivity,当用户点击发送按钮启动一个新的Activity。

 

Respond to the Send Button
响应发送按钮


--------------------------------------------------------------------------------
1.In Android Studio, from the res/layout directory, edit the activity_my.xml file.
1.在Android Studio,从res/layout目录,编辑activity_my.xml文件。

2.To the <Button> element, add the android:onClick attribute.
2.<按钮>元素中,添加了android:onclick属性。
res/layout/activity_my.xml
<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的方法名称。

3.In the java/com.mycompany.myfirstapp directory, open the MyActivity.java file.
3.在 java/com.mycompany.myfirstapp目录中,打开MyActivity.java文件。

4.Within the MyActivity class, add the sendMessage() method stub shown below.
4.在MyActivity类中,添加如下所示的sendMessage()方法存根。
res/layout/activity_my.xml
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/button_send"
    android:onClick="sendMessage" />

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)
?要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.
接下来,您将填写此方法来读取文本字段的内容,并提供文本到另一个Activity。

 

Build an Intent
构建一个Intent

 

1. In MyActivity.java, inside the sendMessage() method, create an Intent to start an activity called DisplayMessageActivity with the following code:
1.在MyActivity.java的sendMessage()方法中,创建一个Intent要启动名为DisplayMessageActivity用下面的代码的活动Activity:
java/com.mycompany.myfirstapp/MyActivity.java
public void sendMessage(View view) {
  Intent intent = new Intent(this, DisplayMessageActivity.class);
}

Note: The reference to DisplayMessageActivity will raise an error if you’re using an IDE such as Android Studio because the class doesn’t exist yet. Ignore the error for now; you’ll create the class soon.
注:参考DisplayMessageActivity会,如果您使用的是IDE抛出一个错误,如Android Studio因为该类还不存在。忽略现在的错误;你很快就会创建类。

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)
?The Class of the app component to which the system should deliver the Intent (in this case, the activity that should be started)
这里使用的构造函数有两个参数:
?一个上下文作为第一个参数(这是因为Activity类是语境的一个子类)
?该应用组件到该系统应提供的意图的等级(在此情况下,应启动的活性)

Android Studio indicates that you must import the Intent class.
Android Studio指示您必须导入Intent类。

 

Intents
意图

 

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. For more information, see Intents and Intent Filters.
一个意图是一个对象,它提供的运行时分开的部件(例如,两个活动Activity)之间的结合。该意图Intent书表示应用程序的“意图做些什么。”您可以使用意图为各种各样的任务,但多数情况下,他们已经习惯了启动另一个活动Activity。欲了解更多信息,请参阅意图和意图过滤器。

2.At the top of the file, import the Intent class:
2.在文件的顶部,导入Intent类:

java/com.mycompany.myfirstapp/MyActivity.java
import android.content.Intent;

Tip: In Android Studio, press Alt + Enter (option + return on Mac) to import missing classes.
提示:在Android Studio里,按Alt+ Enter键(在Mac上选项+返回)导入缺少类。

3.Inside the sendMessage() method, use findViewById() to get the EditText element.
3.在sendMessage()方法里面,使用findViewById()来获得的EditText元素。

java/com.mycompany.myfirstapp/MyActivity.java
public void sendMessage(View view) {
  Intent intent = new Intent(this, DisplayMessageActivity.class);
  EditText editText = (EditText) findViewById(R.id.edit_message);
}

4.At the top of the file, import the EditText class.
4.在文件的顶部,导入的EditText类。

In Android Studio, press Alt + Enter (option + return on Mac) to import missing classes.
在Android Studio,按Alt+ Enter键(在Mac上选项+返回)导入缺少类。

5.Assign the text to a local message variable, and use the putExtra() method to add its text value to the intent.
5.指定文本到本地消息变量,并使用putExtra()方法来它的文本值添加到意图。

java/com.mycompany.myfirstapp/MyActivity.java
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);
}


An Intent can carry 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.
一个Intent可以携带数据类型键值调用extras。该putExtra()方法中的第一个参数的键名,并在第二个参数的值。

6.At the top of the MyActivity class, add the EXTRA_MESSAGE definition as follows:
6.在MyActivity类的顶部,如下添加EXTRA_MESSAGE定义:

java/com.mycompany.myfirstapp/MyActivity.java
public class MyActivity extends ActionBarActivity {
    public final static String EXTRA_MESSAGE = "com.mycompany.myfirstapp.MESSAGE";
    ...
}


For the next activity to query the extra data, you should define the key for your intent‘s extra using a public constant. It‘s generally a good practice to define keys for intent extras using your app‘s package name as a prefix. This ensures the keys are unique, in case your app interacts with other apps.
在接下来的活动Activity查询额外的数据,你应该定义键你的意图的额外使用公共常数。它通常以使用您的应用程序包名作为前缀的意图额外定义键一个很好的做法。这可确保密钥是唯一的,如果你的应用程序与其他应用程序进行交互。

7.In the sendMessage() method, to finish the intent, call the startActivity() method, passing it the Intent object created in step 1.
7.在sendMessage()方法,完成意图Intent,调用startActivity()方法,传递在步骤1中创建的Intent对象。

With this new code, the complete sendMessage() method that‘s invoked by the Send button now looks like this:
有了这个新的代码,这是通过发送按钮调用现在完整的sendMessage()方法是这样的:

java/com.mycompany.myfirstapp/MyActivity.java
/** 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);
}

The system receives this call and starts an instance of the Activity specified by the Intent. Now you need to create the DisplayMessageActivity class in order for this to work.
该系统接收该调用并开始由意图指定的活动Activity的一个实例。现在,你需要为了这个工作创造DisplayMessageActivity类。

 

Create the Second Activity
创建第二个活动Activity


--------------------------------------------------------------------------------

All subclasses of Activity must implement the onCreate() method. This method is where the activity receives the intent with the message, then renders the message. Also, the onCreate() method must define the activity layout with the setContentView() method. This is where the activity performs the initial setup of the activity components.
活动Activity的所有子类必须实现的onCreate()方法。这种方法是,其中的活性接收与消息的意图,那么呈现该消息。此外, onCreate()方法必须定义与的setContentView()方法的活性布局。这是其中的活性进行活性成分的初始设置。

Create a new activity using Android Studio
创建采用Android Studio的新活动Activity
 技术分享
Figure 1. The new activity wizard in Android Studio.
图1. Android Studio中的新的活动Activity的向导。

Android Studio includes a stub for the onCreate() method when you create a new activity.
Android Studio包括存根当你创建一个新的活动Activity onCreate()方法。

1.In Android Studio, in the java directory, select the package, com.mycompany.myfirstapp, right-click, and select New > Activity > Blank Activity.
1.在Android Studio,在java目录,选择软件包,com.mycompany.myfirstapp,单击鼠标右键,并选择New>活动Activity>空白活动Activity。

2.In the Choose options window, fill in the activity details: ?Activity Name: DisplayMessageActivity
?Layout Name: activity_display_message
?Title: My Message
?Hierarchical Parent: com.mycompany.myfirstapp.MyActivity
?Package name: com.mycompany.myfirstapp
2.在选择选项窗口,填写活动Activity的详细信息:?Activity名称:DisplayMessageActivity
?布局名称:activity_display_message
?标题:我留言
?分层父:com.mycompany.myfirstapp.MyActivity
?包名称:com.mycompany.myfirstapp

Click Finish.
点击完成。

3.Open the DisplayMessageActivity.java file.
3.打开DisplayMessageActivity.java文件。

The class already includes an implementation of the required onCreate() method. You will update the implementation of this method later. It also includes an implementation of onOptionsItemSelected(), which handles the action bar‘s Up behavior. Keep these two methods as they are for now.
类已经包含所需 onCreate()方法的实现。您稍后将更新此方法的实现。它还包括一个实现onOptionsItemSelected()中,它处理的操作栏的最高行为。保持这两个方法,因为它们现在。
 
4. Remove the onCreateOptionsMenu() method.
4.拆下onCreateOptionsMenu()方法。

You won‘t need it for this app.
在应用程序里,你并不会需要它。
 
If you‘re developing with Android Studio, 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.
如果您正在开发采用Android Studio,您现在可以运行应用程序,但没有太大的反应。点击发送按钮启动的第二个活动Activity,但它采用的是默认的“Hello world”由模板提供的布局。你很快就会升级到而不是显示自定义文本视图的活动Activity。

 

Create the activity without Android Studio
创建一个不使用Android Studio的活动Activity

 

If you‘re using a different IDE or the command line tools, do the following:
1.Create a new file named DisplayMessageActivity.java in the project‘s src/ directory, next to the original MyActivity.java file.
2.Add the following code to the file:
如果您使用的是不同的IDE或命令行工具,请执行以下操作:
1.创建一个名为DisplayMessageActivity.java项目的src/目录下的新文件,旁边,原来MyActivity.java文件。
2.将以下代码添加到文件:

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


Note: If you are using an IDE other than Android Studio, 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.
注:如果您使用的是IDE比Android Studio等,您的项目不包含的请求的setContentView的activity_display_message布局()。这是可以的,因为你会在以后更新此方法并不会使用该布局。

3.To your strings.xml file, add the new activity‘s title as follows:
3.您的strings.xml文件,添加新的活动的标题如下:

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

4.In your manifest file, AndroidManifest.xml, within the Application element, add the <activity> element for your DisplayMessageActivity class, as follows:
4.在你的manifest文件,AndroidManifest.xml中,应用程序元素中,添加<活动>元素为您DisplayMessageActivity类,如下所示:

<application ... >
    ...
    <activity
        android:name="com.mycompany.myfirstapp.DisplayMessageActivity"
        android:label="@string/title_activity_display_message"
        android:parentActivityName="com.mycompany.myfirstapp.MyActivity" >
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value=http://www.mamicode.com/"com.mycompany.myfirstapp.MyActivity" />
    </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 <meta-data> element as shown here.
Android :parentActivityName属性声明应用程序的逻辑层次结构中本次活动的父活动的名称。该系统使用这个值来实现默认的导航行为,如向上导航在Android4.1(API等级16)和更高。您可以通过使用支持库和添加<元数据>元素,如下所示提供相同的导航行为较旧版本的Android。

Note: Your Android SDK should already include the latest Android Support Library, which you installed during the Adding SDK Packages step. When using the templates in Android Studio, 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 Android Studio, 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支持库,您在添加SDK软件包安装的步骤。当使用Android的Studio中的模板,支持库会自动添加到您的应用程序的项目(您可以看到该库的JAR文件中列出的Android下的相关性)。如果你不使用Android Studio,你需要的库手动添加到您的项目,遵循建立支持库,然后返回莅临指导。


If you‘re using a different IDE than Android Studio, don‘t worry that the app won‘t yet compile. You‘ll soon update the activity to display a custom text view.
如果您使用的是不同的IDE比Android Studio,不用担心应用程序将尚未编译。你很快就会更新显示自定义文本视图的活动。

 

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 the intent.
每一个活动是由一个Intent调用,不管用户如何导航那里。你可以得到你开始的活动通过调用getIntent(的意图),并取回包含的意图中的数据。

1.In the java/com.mycompany.myfirstapp directory, edit the DisplayMessageActivity.java file.
1.在Java/ com.mycompany.myfirstapp目录,编辑DisplayMessageActivity.java文件。

2.In the onCreate() method, remove the following line:
2.在OnCreate()方法,删除以下行:

setContentView(R.layout.activity_display_message);

3.Get the intent and assign it to a local variable.
3.获取的意图,并将其分配到一个局部变量。

Intent intent = getIntent();

4.At the top of the file, import the Intent class.
4.在文件的顶部,导入Intent类。

In Android Studio, press Alt + Enter (option + return on Mac) to import missing classes.
在Android Studio,按Alt+ Enter键(在Mac选项+返回)导入缺少类。

5.Extract the message delivered by MyActivity with the getStringExtra() method.
5.提取由MyActivity与getStringExtra()方法传递消息。

String message = intent.getStringExtra(MyActivity.EXTRA_MESSAGE);

Display the Message
显示消息
--------------------------------------------------------------------------------
1.In the onCreate() method, create a TextView object.
1.在OnCreate()方法中,创建一个TextView对象。
TextView textView = new TextView(this);

2.Set the text size and message with setText().
2.设置文字大小和消息的setText()。

textView.setTextSize(40);
textView.setText(message);

3.Then add the TextView as the root view of the activity’s layout by passing it to setContentView().
3.然后通过它传递给的setContentView添加的TextView作为活动布局的根视图()。

setContentView(textView);

4.At the top of the file, import the TextView class.
4.在文件的顶部,导入的TextView类。

In Android Studio, press Alt + Enter (option + return on Mac) to import missing classes.
在Android Studio,按Alt+ Enter键(在Mac上选项+返回)导入缺少类。

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(MyActivity.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.
现在,您可以运行应用程序。当它打开时,请在文本字段的消息,点击发送,并在第二个活动出现的消息。

技术分享

Figure 2. Both activities in the final app, running on Android 4.4.
图2.这两项活动在最后的应用程序,在Android4.4上运行。

That‘s it, you‘ve built your first Android app!
就是这样,你已经建立了你的第一个Android应用程序!

To learn more, follow the link below to the next class.
要了解更多信息,请按照下面的隔壁班的链接。

本文翻译自:https://developer.android.com/training/basics/firstapp/starting-activity.html

Android官方入门文档[4]启动另一个Activity