如何在我的构造函数中使用自定义对象制作我的自定义模型Parcelable

时间:2015-12-24 17:37:18

标签: java android parcelable custom-object

这是我的课程,我试图让它成为Parcelable,正如你在代码中看到的那样,我在代码的某些地方陷入困境:

public class CommentModel implements Parcelable{

    String      COMMENT_CONTENT;
    String      COMMENT_ID;
    UserModel   COMMENT_ACTOR;

    public CommentModel(String comment_content, String comment_id, UserModel comment_user){

        this.COMMENT_CONTENT    = comment_content;
        this.COMMENT_ID         = comment_id;
        this.COMMENT_ACTOR      = comment_user;

    }

    /*== constructor to rebuild object from the Parcel ==*/
    public CommentModel(Parcel source) {

        this.COMMENT_CONTENT                = source.readString();
        this.COMMENT_ID                     = source.readString();

        // This is where I'm stuck!
        this.COMMENT_ACTOR                  = source............;
    }

    public String getContent(){
        return this.COMMENT_CONTENT;
    }

    public void setContent(String content){
        this.COMMENT_CONTENT    = content;
    }

    public String getId(){
        return this.COMMENT_ID;
    }

    public void setId(String id){
        this.COMMENT_ID = id;
    }

    public UserModel getActor(){
        return this.COMMENT_ACTOR;
    }

    public void setActor(UserModel actor){
        this.COMMENT_ACTOR  = actor;
    }

    @Override
    public int describeContents() {
        return 0;
    }

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

        dest.writeString(COMMENT_CONTENT);
        dest.writeString(COMMENT_ID);

        // This is where I'm stuck too! :(
        dest.write.....
    }

    public static final Parcelable.Creator<CommentModel> CREATOR = new Creator<CommentModel>() {

        @Override
        public CommentModel[] newArray(int size) {
            return new CommentModel[size];
        }

        @Override
        public CommentModel createFromParcel(Parcel source) {
            return new CommentModel(source);
        }
    };


}

应该怎么做? 完全可能吗?如果不是如何处理这个问题?

P.s:我的UserModel()当然也是Parcelable。

1 个答案:

答案 0 :(得分:2)

如果UserModelParcelable,您可以使用writeParcelable来编写对象,并readParcelable将其读回。 E.g。

dest.writeParcelable(COMMENT_ACTOR, flages);

写,

COMMENT_ACTOR = source.readParcelable(UserModel.class.getClassLoader());

读回来。