Byr*_*ron 87 android android-intent android-activity
我在Parcelable下面创建了一个对象,我的对象包含一个ListProducts.在我的构造函数中,如何处理重新创建我Parcelable的List?
我检查了包裹中可用的所有方法,所有可用的方法都是readArrayList(ClassLoader).我不确定这是不是最好的方法,你的建议真的很值得赞赏.
public class Outfits implements Parcelable {
private String url;
private String name;
private List<Product> products;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Product> getProducts() {
return products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
public void writeToParcel(Parcel dest, int flags) {
Log.v("", "writeToParcel..." + flags);
dest.writeString(url);
dest.writeString(name);
dest.writeList(products);
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public Outfits createFromParcel(Parcel in) {
return new Outfits(in);
}
public Outfits[] newArray(int size) {
return new Outfits[size];
}
};
@Override
public int describeContents() {
return 0;
}
/*** Here how do I populate my List of Products ***/
private Outfits(Parcel in) {
url = in.readString();
name = in.readString();
products = in.read ???????;
}
}
Run Code Online (Sandbox Code Playgroud)
Ale*_*man 96
如果类Product与parcelable协议兼容,则以下内容应根据文档进行操作.
products = new ArrayList<Product>();
in.readList(products, Product.class.getClassLoader());
Run Code Online (Sandbox Code Playgroud)
cod*_*zjx 38
首先,您的Product对象必须实现Parcelable.
然后,dest.writeTypedList(products)在writeToParcel()方法中使用.
最后,使用以下代码来解析列表:
products = new ArrayList<Product>();
in.readTypedList(products, Product.CREATOR);
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请参阅官方文件:
小智 5
以我的个人经验,http://www.parcelabler.com/是一个很棒的网站。您只需创建您的课程,然后将其复制粘贴到网站中,即可生成该课程的Parcelable版本。
我使用名为“ Theme”的类进行了测试,该类包含以下变量:
private String name;
private int image;
private List<Card> cards;
Run Code Online (Sandbox Code Playgroud)
writeToParcel函数变为:
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeInt(image);
if (cards == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeList(cards);
}
}
Run Code Online (Sandbox Code Playgroud)
生成的构造函数:
protected Theme(Parcel in) {
name = in.readString();
image = in.readInt();
if (in.readByte() == 0x01) {
cards = new ArrayList<Card>();
in.readList(cards, Card.class.getClassLoader());
} else {
cards = null;
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:确保Card对象也是可包裹的!
| 归档时间: |
|
| 查看次数: |
70755 次 |
| 最近记录: |