Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 技術基礎

Intent 進階:Activity 之間的雙向資料傳遞

編輯:Android 技術基礎

Android 中 Activity 之間的跳轉靠 Intent 完成。本文用一個小例子把「去」與「回」兩段路都走通:MainActivity 用 startActivityForResult() 打開 OtherActivity 並帶一個參數過去,OtherActivity 返回時再用 Bundle 批次回傳多筆資料。

一、版面配置

1.1 activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/open"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="打開另一個 Activity (OtherActivity)" />

    <TextView
        android:id="@+id/result"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="顯示 OtherActivity 返回結果" />
</LinearLayout>

1.2 otheractivity.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="返回 MainActivity" />

    <TextView
        android:id="@+id/prompt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="顯示 MainActivity 傳來的值" />
</LinearLayout>

二、程式碼

2.1 MainActivity.java:出發並接收回傳

package com.genwoxue.intent_b;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

    private TextView tvResult = null;
    private Button btnOpen = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tvResult = (TextView) super.findViewById(R.id.result);
        btnOpen  = (Button) super.findViewById(R.id.open);

        // 出發:帶一個參數過去,並要求回傳結果
        btnOpen.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, OtherActivity.class);
                intent.putExtra("prompt", "你知道蔣老夫子的電話與郵箱嗎?");
                MainActivity.this.startActivityForResult(intent, 1);
            }
        });
    }

    // 回程:接收 OtherActivity 回傳的資料
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (resultCode) {
            case RESULT_OK:
                super.onActivityResult(requestCode, resultCode, data);
                // 多筆資料用 Bundle 承載
                Bundle bundle = data.getExtras();
                String employeeName = bundle.getString("employeeName");
                String mobile = bundle.getString("mobile");
                String email = bundle.getString("email");
                tvResult.setText("☆☆☆☆☆☆返回結果☆☆☆☆☆☆"
                        + "\n員工:" + employeeName
                        + "\n手機號碼:" + mobile
                        + "\n電子郵件:" + email);
                break;
            case RESULT_CANCELED:
                tvResult.setText("操作取消");
                break;
            default:
                break;
        }
    }
}

這裡的關鍵是 startActivityForResult(intent, 1) 取代了普通的 startActivity(),並在 onActivityResult() 中依 resultCode 分別處理「正常返回」與「使用者按返回鍵取消」兩種結局。

2.2 OtherActivity.java:接收並回傳

package com.genwoxue.intent_b;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class OtherActivity extends Activity {

    private TextView tvPrompt = null;
    private Button btnBack = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_other);

        tvPrompt = (TextView) super.findViewById(R.id.prompt);
        btnBack  = (Button) super.findViewById(R.id.back);

        // 接收上一個 Activity 傳來的值
        Intent intent = super.getIntent();
        String url = intent.getStringExtra("prompt");
        tvPrompt.setText(url);

        // 回程:用 Bundle 打包多筆資料,透過 setResult 交回去
        btnBack.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("employeeName", "蔣老夫子");
                bundle.putString("mobile", "139037100xx");
                bundle.putString("email", "hello@genwoxue.com");

                Intent intent = new Intent(OtherActivity.this, MainActivity.class);
                intent.putExtras(bundle);
                OtherActivity.this.setResult(RESULT_OK, intent);
                OtherActivity.this.finish();     // 關掉自己,回到上一頁
            }
        });
    }
}

三個動作要記住:用 getIntent() 取得呼叫方傳來的 Intent;用 Bundle 打包要回傳的資料並 putExtras();最後呼叫 setResult(RESULT_OK, intent) 再 finish()。順序很重要——一定要先 setResult 再 finish,否則呼叫方會收到 RESULT_CANCELED。

三、註冊 Activity

別忘了在 AndroidManifest.xml 中登記新的 Activity,漏了會直接 ActivityNotFoundException:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.genwoxue.intent_b"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        <activity
            android:name="com.genwoxue.intent_b.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity
            android:name="com.genwoxue.intent_b.OtherActivity" >
        </activity>

    </application>
</manifest>

MainActivity 需要 intent-filter(它是啟動入口),而 OtherActivity 只由程式內部明確指定,因此不需要 filter,只要 android:name 正確即可。

四、執行結果

五、重點整理

· 單值傳遞用 putExtra(key, value),接收端用 getXxxExtra(key);
· 多值傳遞用 Bundle 裝好再一次 putExtras(bundle),接收端用 getExtras();
· 需要回傳就必須改用 startActivityForResult(),接收端在 onActivityResult() 中處理,並記得判斷 resultCode;
· 回傳前務必先 setResult() 再 finish()。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved