首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android Activity 傳遞對象:實現 Serializable 接口配合 Intent

     編輯:程式設計綜合問答

定義可序列化類


public class Customer implements Serializable {
    private static final long serialVersionUID = 1L;
    private String firstName, lastName, address;
    private int age;

    public Customer(String fn, String ln, int age, String addr) {
        this.firstName = fn; this.lastName = ln; this.age = age; this.address = addr;
    }
    // getter/setter...
}

發送端


Customer customer = new Customer("John", "Doe", 30, "123 Street");
Intent intent = new Intent(this, DetailActivity.class);
intent.putExtra("customer", customer); // Serializable 自動支持
startActivity(intent);

接收端


Customer customer = (Customer) getIntent().getSerializableExtra("customer");
if (customer != null) {
    textView.setText(customer.getFirstName() + " " + customer.getLastName());
}

替代方案:Parcelable (性能更好)


public class Customer implements Parcelable {
    // 字段...
    protected Customer(Parcel in) {
        firstName = in.readString();
        lastName = in.readString();
        age = in.readInt();
        address = in.readString();
    }
    @Override public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(firstName);
        dest.writeString(lastName);
        dest.writeInt(age);
        dest.writeString(address);
    }
    public static final Creator CREATOR = new Creator() {
        @Override public Customer createFromParcel(Parcel in) { return new Customer(in); }
        @Override public Customer[] newArray(int size) { return new Customer[size]; }
    };
}

Android Studio 右鍵 Generate → Parcelable 可自動生成樣板代碼。

大數據傳遞

超過 1MB (Binder 事務緩衝區限制) 需用共享內存、文件、數據庫或 Application 单例中轉。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved