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

Bundle 用法解析:把資料打包放進 Intent

編輯:Android 開發實例

SDK 對 Bundle 的描述是:A mapping from String values to various Parcelable types——一個從字串鍵值對應到各種 Parcelable 型別的映射表。它的價值在於幫你把資料打包塞進 Intent,讓跨 Activity 傳值變得乾淨俐落。

典型流程:以 ListView 點擊為例

protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);

    // 取得被點選項的 HashMap
    HashMap<String, String> map =
        (HashMap<String, String>) lv.getItemAtPosition(position);
    String type = map.get("Type");

    Intent i = new Intent(this, TitleActivity.class);
    Bundle mBundle = new Bundle();
    mBundle.putString("type", type);
    i.putExtras(mBundle);
    startActivity(i);
}

整段程式碼其實只有三步:

  1. 建立 Bundle 物件,用 putString(鍵, 值) 把資料放進去。
  2. 把 Bundle 塞進 Intent。
  3. 用 Intent 啟動另一個 Activity。

接收端怎麼把資料拿出來

bundle = getIntent().getExtras();
if (bundle != null) {
    Type = bundle.getString("type");
    if (Type != null) {
        // 依型別從資料庫讀出對應內容
        cur = myDBadapter.getTitle(new String[] { Type });
    }
}

這裡有兩個重點:

  • Bundle 可以透過 Activity.getIntent().getExtras() 取回。也就是說,啟動目前這個 Activity 的那個 Intent 物件,是靠 getIntent() 找回來的。
  • 取出資料用 Bundle 的 getString()(或其他對應型別的 getter)即可,鍵名稱必須與放入時一致。

這就是 Bundle 最經典的用法:把資料包裹起來放進 Intent,目的就是為了傳輸。

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