Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android Activity 之間傳值完整解析:Intent、Bundle 與回傳結果

編輯:關於 Android 程式設計

多頁面應用一定會遇到「A 頁面把資料帶到 B 頁面」,以及「B 頁面處理完把結果送回 A」。Android 的做法是以 Intent 承載資料、Bundle 負責包裝,再用 startActivityForResult() 取得回傳。以下用一個完整範例走過整個流程。

主 Activity:出發並等待回傳

package com.chaoyang.activity;

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

public class MainActivity extends Activity {

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

        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // 指定要啟動的元件
                Intent intent = new Intent(MainActivity.this, TheOtherActivity.class);
                // 等價寫法:
                // intent.setClass(MainActivity.this, TheOtherActivity.class);
                // intent.setComponent(new ComponentName(MainActivity.this, TheOtherActivity.class));

                // 寫法一:直接 putExtra(看起來最簡潔)
                // intent.putExtra("name", "dinglang");
                // intent.putExtra("age", 22);

                // 寫法二:先組 Bundle 再整體塞入
                Bundle bundle = new Bundle();
                bundle.putString("name", "dinglang");
                bundle.putInt("age", 22);
                intent.putExtras(bundle);

                // 不需要回傳值時可直接用 startActivity(intent)
                // 需要回傳值時改用 startActivityForResult,第二個參數是請求碼
                startActivityForResult(intent, 100);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Toast.makeText(this, data.getStringExtra("result"), 1).show();
    }
}

為什麼兩種寫法本質相同?因為 putExtra(String, String) 內部會檢查這個 Intent 是否已有 Bundle,沒有的話就幫你建一個,之後所有 extra 都放進同一個 Bundle 裡。看過原始碼就會發現兩條路殊途同歸。

目標 Activity:收值並回傳

package com.chaoyang.activity;

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

public class TheOtherActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.other);

        // 取得啟動自己的 Intent
        Intent intent = this.getIntent();
        String name = intent.getStringExtra("name");
        int age = intent.getExtras().getInt("age");   // 寫法二對應的取值方式

        TextView textView = (TextView) this.findViewById(R.id.result);
        textView.setText("姓名:" + name + "  年齡:" + age);

        Button button = (Button) this.findViewById(R.id.close);
        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent data = new Intent();
                data.putExtra("result", "這是處理結果");
                setResult(20, data);   // 設定結果碼與回傳資料
                finish();              // 關閉自己,回到上一頁
            }
        });
    }
}

兩個版面檔

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

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="打開 OtherActivity" />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TextView
        android:id="@+id/result"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="這是 OtherActivity" />

    <Button
        android:id="@+id/close"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="關閉 Activity" />
</LinearLayout>

別忘了註冊新的 Activity

<activity android:name=".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 啟動時會直接丟 ActivityNotFoundException -->
<activity android:name=".TheOtherActivity" android:label="the other Activity" />

關鍵知識點整理

Bundle 的角色。它用來攜帶資料,概念上類似 Map,存放 key-value 形式的配對,並針對常見型別提供 putString()/getString()、putInt()/getInt() 等方法。內部實際上是用 HashMap<String, Object> 保存資料。它的價值在於可序列化、可跨進程傳遞,因此不只 Intent 用它,onSaveInstanceState() 也用它。

請求碼與結果碼。onActivityResult() 的第一個參數是請求碼,就是你呼叫 startActivityForResult() 時傳入的值,用來在多個可回傳的頁面中分辨「這次回來的是誰」;第二個參數是結果碼,由目標頁透過 setResult() 設定,用來標示處理的結果狀態。兩者都只是你自己定義的識別碼,和 HTTP 的 200/404 完全無關,依業務需求自行約定即可。

現代寫法。上述 API 至今仍可用,但官方已推薦改用 Activity Result API:註冊 registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), callback),可省掉請求碼常數與 onActivityResult() 的覆寫,也能避開整頁重啟時狀態遺失的問題。若資料只是要在同一個 Task 內共享,也可考慮 ViewModel 或 Fragment Result API。

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