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

Android Activity 間資料傳遞:Bundle 物件的應用

編輯:關於 Android 程式設計

在應用中跳轉到另一個 Activity 時,往往需要把資料一併帶過去。此時 Bundle 物件便是最貼心的助手。它類似於 Map<Key, Value> 結構,能把各種類型的資料打包傳遞。

發送端:在 MainActivity 中打包資料

Intent intent = new Intent(Context context, Class<?> class);
// new 一個 Bundle 物件,並將要傳遞的資料放入
Bundle bundle = new Bundle();
bundle.putString("name", "Livingstone");
bundle.putXXX(XXXKey, XXXValue);
// 將 Bundle 物件加入 Intent
intent.putExtras(bundle);
startActivity(intent); // 啟動對應的 Activity

接收端:在 BActivity 中取出資料

Bundle bundle = this.getIntent().getExtras(); // 取得封裝了資料的 Bundle
String name = bundle.getString("name");          // 取得 name 對應的值
// 放入時是什麼型別,取出時就用什麼型別的方法:bundle.getXXX(XXXKey)

傳遞物件:Parcelable 與 Serializable

以上是基本資料型別的傳遞。若需要傳遞自訂物件,可以讓該物件實作 Parcelable 或 Serializable 介面,再透過 Bundle.putParcelable() 或 putSerializable() 加入 Bundle。目標頁面則分別用 Intent.getParcelableExtra() 與 getSerializableExtra() 取出。

此外,Intent.putExtra(Key, Value) 其實也能傳遞資料,包括上述物件。Serializable 的實作相當簡單,這裡重點說明 Parcelable:

實作 Parcelable 介面

public class Book implements Parcelable {
    private String bookName;
    private String author;

    // 必須定義一個 CREATOR 靜態成員,否則會報錯
    public static final Parcelable.Creator CREATOR = new Creator() {
        @Override
        public Book createFromParcel(Parcel source) {
            // 從 Parcel 讀取資料,順序需與寫入時一致
            Book book = new Book();
            book.setAuthor(source.readString());
            book.setBookName(source.readString());
            return book;
        }
        @Override
        public Book[] newArray(int size) {
            return new Book[size];
        }
    };
    @Override
    public int describeContents() {
        return 0;
    }
    @Override
    // 將資料寫入 Parcel,順序需與讀取時一致
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(author);
        dest.writeString(bookName);
    }
}

關於 Parcel,它是一個 final 類別,專門用於讀寫各種資料,核心方法不外乎 writeValue(Object) 與 read(ClassLoader)。要牢記的關鍵是:寫入與讀取的順序必須完全一致,否則資料會錯位。

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