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

Android 頁面通訊入門:用 Bundle 在兩個 Activity 間傳遞資料

編輯:關於 Android 程式設計

Activity 與 Activity 之間要交換資料,最常見也最輕量的做法就是搭配 Intent 使用 Bundle。下面以一個報價場景為例:清單頁 ListViewActivity 點選某一筆物料後,把物料名稱、規格與 id 帶到詳情頁 ReplyActivity。

一、出發頁:把資料塞進 Bundle

// 建立 Intent 並指定目標 Activity
Intent intent = new Intent();
intent.setClass(ListViewActivity.this, ReplyActivity.class);

// 將需要傳遞的欄位放入 Bundle
Bundle bundle = new Bundle();
bundle.putString("materialName", map.get("materialName").toString());
bundle.putString("materialFormat", map.get("materialFormat").toString());
bundle.putString("mapId", map.get("mapId").toString());

intent.putExtras(bundle);
startActivity(intent);

這裡有兩個細節值得注意:一是 setClass() 明確指出要啟動哪個元件,屬於顯式 Intent,系統不必額外做比對,效率較好;二是 Bundle 內部以 key-value 形式存放,key 必須在兩頁之間保持一致。

二、目的頁:把資料取出來

到了 ReplyActivity,只要呼叫 getIntent() 就能拿到啟動自己的那個 Intent,再從中取出 Bundle:

// 取得啟動本頁的 Intent
Intent intent = this.getIntent();

// 取出 Bundle 內容
Bundle bundle = intent.getExtras();
String materialName = bundle.getString("materialName");
String materialFormat = bundle.getString("materialFormat");
String mapId = bundle.getString("mapId");

三、Bundle 的適用範圍

Bundle 能承載的不只是基本型別與字串,也可以放入实现了 Parcelable 或 Serializable 介面的自訂物件。若資料量較大或結構較複雜,建議改成由目的頁透過 ContentProvider 或資料庫查詢,避免 Bundle 過肥造成 TransactionTooLargeException。

此外,若需要在目的頁結束後把結果帶回來,就不能用 startActivity(),而要改用 startActivityForResult() 搭配 setResult(),這是單向傳遞與雙向回傳的分水嶺。

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