1. 程式人生 > >[Andriod官方訓練教程]建立你的第一個App之開始另一個Activity

[Andriod官方訓練教程]建立你的第一個App之開始另一個Activity

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

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.

在完成上一節課後,你已經有了一個顯示一個activity(單獨一個螢幕)的app,它包含一個文字框和一個按鍵。在這節課裡,你將會向MainActivity新增一些程式碼,使得使用者點選Send按鍵後開始一個新的activity。

Respond to the Send Button —— 響應傳送按鍵

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

為了響應按鍵的點選事件,開啟activity_main.xml

<Buttonandroid: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 */publicvoid sendMessage(View view){// Do something in response to button}

This requires that you import the View class:

這要求你匯入View 類:

import android.view.View;

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

提示:在Eclipse裡,按 Ctrl + Shift + O 來匯入缺少的類(Mac裡是Cmd + Shift + O)。

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 是public的
  • Have a void return value 返回值為void
  • 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 —— 建立一個Intent

An  is an object that provides runtime binding between separate components (such as two activities). The  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.

一個 是一個在不同的部件(例如兩個activities)之間提供動態繫結的物件。 代表了一個app“想要做什麼”。你可以為很多工使用intents,但是大多數它們被用於開始另一個activity。

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

sendMessage() 方法裡,建立一個 an  來開始一個叫DisplayMessageActivity的activities:

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

The constructor used here takes two parameters:

這裡的構造器接受兩個引數:

  • A  as its first parameter (this is used because the  class is a subclass of ) 第一個引數是一個
  • The Class of the app component to which the system should deliver the  (in this case, the activity that should be started) 系統應該將該傳送給app中的哪個Class (在本情況下,就是應該被啟動的那個activity)

Sending an intent to other apps

The intent created in this lesson is what's considered an explicit intent, because the  specifies the exact app component to which the intent should be given. However, intents can also be implicit, in which case the  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 parameters. For more information, see the class about Interacting with Other Apps.

向其他apps傳送一個intent

這節課中建立的intent被認為是一個顯式的intent,因為該指定了它應該被髮送給的明確的app部件。 然而,intents同樣可以是隱式的,在這種情況下 沒有指定希望的部件,而是允許裝置上安裝的任何app來響應該intent,只要它滿足引數中指定的動作的元資料規格。更多的資訊,請見 Interacting with Other Apps 一課。

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.

注意: 如果你正在使用一個IDE,例如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  to get the  element and add its text value to the intent:

一個Intent不僅僅允許你開啟另一個activity,它還可以向activity帶來捆綁的資料。在sendMessage()

Intent intent =newIntent(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 for android.content.Intent and android.widget.EditText. You'll define the EXTRA_MESSAGE constant in a moment.

注意:你現在需要匯入 android.content.Intent 和 android.widget.EditText。稍後你將會定義EXTRA_MESSAGE 常量。

An  can carry a collection of various data types as key-value pairs called extras. The method takes the key name in the first parameter and the value in the second parameter.

一個 可以攜帶一系列資料型別作為鍵-值對,這被稱為extrasputExtra()方法將第一個引數作為鍵名,第二個引數作為值。

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查詢額外的資料,你應該使用公有常量為你的intent的extra定義鍵。因此,在MainActivity 類的頂部新增EXTRA_MESSAGE 的定義。

publicclassMainActivityextendsActivity{publicfinalstaticString 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.

使用你的app的包名作為一個字首來定義鍵,通常這是一個很好的習慣。這確保它們是唯一的,如果你app要和其他app互動的話。

Start the Second Activity —— 開始第二個Activity

To start an activity, call  and pass it your . The system receives this call and starts an instance of the  specified by the .

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

有了這個新的程式碼,完整的sendMessage() (將被Send按鍵呼叫)方法如下:

/** Called when the user clicks the Send button */publicvoid 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 the DisplayMessageActivity class 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:

使用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
    • Title: My Message
    • Hierarchial Parent: com.example.myfirstapp.MainActivity
    • Navigation Type: None

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

如果你使用一個不同的IDE或者是命令列工具,在專案的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  method. 該類已經包含了需要的 方法的一個實現。
  • There's also an implementation of the  method, but you won't need it for this app so you can remove it. 這裡還有一個 方法的實現,但在這個app裡你將不會用到它,因此你可以把它刪除了。
  • There's also an implementation of  which handles the behavior for the action bar's Up behavior. Keep this one the way it is. 同時還有一個 方法的實現,它負責工具欄上Up 的行為。不用管它。

Because the  APIs are available only on  (API level 11) and higher, you must add a condition around the  method to check the current platform version. Additionally, you must add the @SuppressLint("NewApi") tag to the  method to avoid lint errors.

因為 APIs 僅在 (API level 11)或更高版本上才可用,你必須在 方法外面新增額外的程式碼來檢查當前的平臺版本。

The DisplayMessageActivity class should now look like this:

現在,DisplayMessageActivity 類應該看起來是這樣的:

publicclassDisplayMessageActivityextendsActivity{@SuppressLint("NewApi")@Overrideprotectedvoid onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_display_message);// Make sure we're running on Honeycomb or higher to use ActionBar APIsif(Build.VERSION.SDK_INT >=Build.VERSION_CODES.HONEYCOMB){// Show the Up button in the action bar.
            getActionBar().setDisplayHomeAsUpEnabled(true);}}@Overridepublicboolean onOptionsItemSelected(MenuItem item){switch(item.getItemId()){case android.R.id.home:NavUtils.navigateUpFromSameTask(this);returntrue;}returnsuper.onOptionsItemSelected(item);}}

If you used an IDE other than Eclipse, update your DisplayMessageActivity class with the above code.

如果你在使用除Eclipse外的其他IDE,請使用上面的程式碼更新你的DisplayMessageActivity 類。

All subclasses of  must implement the  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  method and is where you should perform initial setup for the activity components.

 的所有子類都必須實現 方法。系統在建立一個新的activity例項時會呼叫它。在這個方法裡,你必須使用 方法定義該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 . That's OK because you will update this method later and won't be using that layout.

注意:如果你正在使用除Eclipse之外的其他IDE,你的專案沒有包含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之外的其他IDE,向strings.xml 檔案新增新的activity的標題:

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

Add it to the manifest —— 將它新增到清單

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

所有的activities必須使用一個 <activity> 元素在你的清單檔案,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時,它建立了一個預設的入口。如果你使用一個不同的IDE,你需要手動新增清單入口。它看起來應該是這樣的:

<application ... >
    ...
    <activityandroid:name="com.example.myfirstapp.DisplayMessageActivity"android:label="@string/title_activity_display_message"android:parentActivityName="com.example.myfirstapp.MainActivity"><meta-dataandroid: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,