为了账号安全,请及时绑定邮箱和手机立即绑定

自定义对象的 Parcelable 实现

自定义对象的 Parcelable 实现

MMTTMM 2021-06-08 17:02:04
我有 3 种 POJO 类型:一个包含成分的 Recipe,然后是包含步骤的成分。下面是我的设置,我正在尝试实现 Parcelable 并且无法确定适当的读写方法:食谱.Java:public class Recipe implements Parcelable {protected List<Ingredients> ingredients;private String id;private String servings;private String name;private String image;private List<Steps> steps;protected Recipe(Parcel in) {    in.createTypedArray(CREATOR.createFromParcel(Ingredients));    in.createTypedArray(Ingredients.);    id = in.readString();    servings = in.readString();    name = in.readString();    image = in.readString();    steps = in.readArrayList(ClassLoader.getSystemClassLoader());}public static final Creator<Ingredients> CREATOR = new Creator<Ingredients>() {    @Override    public Ingredients createFromParcel(Parcel parcel) {        return new Ingredients(parcel);    }    @Override    public Ingredients[] newArray(int i) {        return new Ingredients[0];    }}public static final Creator<Recipe> CREATOR = new Creator<Recipe>() {    @Override    public Recipe createFromParcel(Parcel in) {        return new Recipe(in);    }    @Override    public Recipe[] newArray(int size) {        return new Recipe[size];    }};public List<Ingredients> getIngredients() {    return ingredients;}public void setIngredients(List<Ingredients> ingredients) {    this.ingredients = ingredients;}public String getId() {    return id;}public void setId(String id) {    this.id = id;}public String getServings() {    return servings;}public void setServings(String servings) {    this.servings = servings;}public String getName() {    return name;}public void setName(String name) {    this.name = name;}public String getImage() {    return image;}public void setImage(String image) {    this.image = image;}public List<Steps> getSteps() {    return steps;}public void setSteps(List<Steps> steps) {    this.steps = steps;}
查看完整描述

1 回答

?
慕神8447489

TA贡献1780条经验 获得超1个赞

我建议您使用Paperparcel等第三方库来减少样板文件。


使用示例:


@PaperParcel // (1)

public final class User implements Parcelable {

    public static final Creator<User> CREATOR = PaperParcelUser.CREATOR; // (2)


    long id; // (3)

    String firstName; // (3)

    String lastName; // (3)


    @Override public int describeContents() {

        return 0;

    }


    @Override public void writeToParcel(Parcel dest, int flags) {

        PaperParcelUser.writeToParcel(this, dest, flags); // (4)

    }

}


查看完整回答
反对 回复 2021-06-10
  • 1 回答
  • 0 关注
  • 147 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信