猿问

自定义对象的 Parcelable 实现

我有 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;

}


MMTTMM
浏览 148回答 1
1回答

慕神8447489

我建议您使用Paperparcel等第三方库来减少样板文件。使用示例:@PaperParcel // (1)public final class User implements Parcelable {&nbsp; &nbsp; public static final Creator<User> CREATOR = PaperParcelUser.CREATOR; // (2)&nbsp; &nbsp; long id; // (3)&nbsp; &nbsp; String firstName; // (3)&nbsp; &nbsp; String lastName; // (3)&nbsp; &nbsp; @Override public int describeContents() {&nbsp; &nbsp; &nbsp; &nbsp; return 0;&nbsp; &nbsp; }&nbsp; &nbsp; @Override public void writeToParcel(Parcel dest, int flags) {&nbsp; &nbsp; &nbsp; &nbsp; PaperParcelUser.writeToParcel(this, dest, flags); // (4)&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答