![](/img/trans.png)
[英]how to pass a thread class object from activity to activity using parcelable
[英]How to pass Parcelable array to fragment and Activity
我正在使用自定義可包裹類。 我需要將此類作為數組傳遞給另一個活動和新片段。 我用谷歌搜索,但是我找到了arrayList但沒有找到數組。 請注意,我需要傳遞數組而不是數組列表。 如何實現呢? 請再次注意,性能是一個大問題。 因此,任何性能消耗少的解決方案都非常受歡迎。
任何幫助將不勝感激。
您可以按以下代碼片段傳遞arrayList。
TestFragment testFragment = new TestFragment();
Bundle args = new Bundle();
args.putSerializable("parsedData", (Serializable)mTestModelList);
testFragment.setArguments(args);
然后在模型中獲取這些可解析的數據,如下所示:
mTestModelList = (List<TestModel>)getArguments().get("parsedData");
是的,序列化比可打包慢。
您可以使用包裹器來實現
當然,可以使用以下命令將ParcelWrapper添加到Android捆綁包中,以從Activity轉移到Activity:
Bundle bundle = new Bundle();
bundle.putParcelable("example", Parcels.wrap(example));
並在onCreate()方法中取消引用:
Example example = Parcels.unwrap(getIntent().getParcelableExtra("example"));
您可以在此處獲得與Parcelable vs Serializable相關的性能的更多詳細信息。
這是寫答案
// write parcelable array
final Bundle arguments = new Bundle();
MyParcelable[] myArray = new MyParcelable[10];
arguments.putParcelableArray("key"myArray);
// read parcelable array
MyParcelable[] myArray = (MyParcelable[])getArguments().getParcelableArray("key");
使用像下面的parcealble數組類
public class ParcelableLaptop implements Parcelable {
private Laptop laptop;
public Laptop getLaptop() {
return laptop;
}
public ParcelableLaptop(Laptop laptop) {
super();
this.laptop = laptop;
}
private ParcelableLaptop(Parcel in) {
laptop = new Laptop();
laptop.setId(in.readInt());
laptop.setBrand(in.readString());
laptop.setPrice(in.readDouble());
laptop.setImageBitmap((Bitmap) in.readParcelable(Bitmap.class
.getClassLoader()));
}
/*
* you can use hashCode() here.
*/
@Override
public int describeContents() {
return 0;
}
/*
* Actual object Serialization/flattening happens here. You need to
* individually Parcel each property of your object.
*/
@Override
public void writeToParcel(Parcel parcel, int flags) {
parcel.writeInt(laptop.getId());
parcel.writeString(laptop.getBrand());
parcel.writeDouble(laptop.getPrice());
parcel.writeParcelable(laptop.getImageBitmap(),
PARCELABLE_WRITE_RETURN_VALUE);
}
/*
* Parcelable interface must also have a static field called CREATOR,
* which is an object implementing the Parcelable.Creator interface.
* Used to un-marshal or de-serialize object from Parcel.
*/
public static final Parcelable.Creator<ParcelableLaptop> CREATOR =
new Parcelable.Creator<ParcelableLaptop>() {
public ParcelableLaptop createFromParcel(Parcel in) {
return new ParcelableLaptop(in);
}
public ParcelableLaptop[] newArray(int size) {
return new ParcelableLaptop[size];
}
};
}
現在制作ParcelableLaptop的Arraylist並使用參數放入bUndle
intent.putParcelableArrayListExtra("laptop", parcelableLaptopArray);
其中parcelableLaptop是模型的Arraylist。 並獲取列表:
Intent intent = getIntent();
ArrayList<ParcelableLaptop> parcelableLaptop = (ParcelableLaptop) intent
.getParcelableArrayListExtra("laptop");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.