在活動之間傳遞自定義物件
也可以使用 Bundle
類將自定義物件傳遞給其他活動。
有兩種方法:
Serializable
介面 - 適用於 Java 和 AndroidParcelable
介面記憶體高效,僅適用於 Android(推薦)
Parcelable
可分割處理比可序列化快得多。其中一個原因是我們明確了序列化過程而不是使用反射來推斷它。理所當然,程式碼已經為此目的進行了大量優化。
public class MyObjects implements Parcelable {
private int age;
private String name;
private ArrayList<String> address;
public MyObjects(String name, int age, ArrayList<String> address) {
this.name = name;
this.age = age;
this.address = address;
}
public MyObjects(Parcel source) {
age = source.readInt();
name = source.readString();
address = source.createStringArrayList();
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(age);
dest.writeString(name);
dest.writeStringList(address);
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
public ArrayList<String> getAddress() {
if (!(address == null))
return address;
else
return new ArrayList<String>();
}
public static final Creator<MyObjects> CREATOR = new Creator<MyObjects>() {
@Override
public MyObjects[] newArray(int size) {
return new MyObjects[size];
}
@Override
public MyObjects createFromParcel(Parcel source) {
return new MyObjects(source);
}
};
}
傳送活動程式碼
MyObject mObject = new MyObject("name","age","Address array here");
//Passing MyOject
Intent mIntent = new Intent(FromActivity.this, ToActivity.class);
mIntent.putExtra("UniqueKey", mObject);
startActivity(mIntent);
在目標活動中接收物件
//Getting MyObjects
Intent mIntent = getIntent();
MyObjects workorder = (MyObjects) mIntent.getParcelable("UniqueKey");
你可以傳遞 Parceble 物件的 Arraylist,如下所示
//Array of MyObjects
ArrayList<MyObject> mUsers;
//Passing MyObject List
Intent mIntent = new Intent(FromActivity.this, ToActivity.class);
mIntent.putParcelableArrayListExtra("UniqueKey", mUsers);
startActivity(mIntent);
//Getting MyObject List
Intent mIntent = getIntent();
ArrayList<MyObjects> mUsers = mIntent.getParcelableArrayList("UniqueKey");
注意: 有過 Android Studio 外掛,如這一個可用來生成程式碼 Parcelable
序列化
傳送活動程式碼
Product product = new Product();
Bundle bundle = new Bundle();
bundle.putSerializable("product", product);
Intent cartIntent = new Intent(mContext, ShowCartActivity.class);
cartIntent.putExtras(bundle);
mContext.startActivity(cartIntent);
在目標活動中接收物件。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = this.getIntent().getExtras();
Product product = null;
if (bundle != null) {
product = (Product) bundle.getSerializable("product");
}
serializable 物件的 Arraylist
:與單個物件傳遞相同
自定義物件應該實現 Serializable
介面。