如何将可包裹对象添加到可包裹对象

时间:2019-05-14 04:23:07

标签: parcelable

我必须将一个Object值传递给其他Activity,因此我找到了使用Parcelable Object的方法。但这是问题

外部ParcelableOjbect(我将其称为“ 1”)具有内部ParcelableOjbect变量(我将其称为“ 2”)。 所以我要做的是将innerParcelableObject添加到externalParcelableObject中。

我要添加的“ 2”已经设置为Parcelable类

但发生错误的行说

writeParcelable(Parcelable, int) in Parcel cannot be applied
to             (State)

这是(1)

ublic class Progress implements Parcelable {
    String time;
    String location;
    State status;                  // <<<----- this is (2)
    String description;

    public Progress(){}
    public Progress(String time, String location, State status, String description) {
        this.time = time;
        this.location = location;
        this.status = status;
        this.description = description;
    }
    protected Progress(Parcel in){
        in.writeString(time);
        in.writeString(location);
        in.writeParcelable(status);   // <<--  the error occured here
        in.writeString(description);
    }

    public static final Creator<Progress> CREATOR = new Creator<Progress>() {
        @Override
        public Progress createFromParcel(Parcel in) {
            return new Progress(in);
        }

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

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

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

    }

    // ... getters and setters

}

这是(2)

public class State implements Parcelable {

    String id;
    String text;

    public State(String id, String text) {
        this.id = id;
        this.text = text;
    }
    protected State(Parcel in) {
        in.writeString(id);
        in.writeString(text);
    }

    public static final Creator<State> CREATOR = new Creator<State>() {
        @Override
        public State createFromParcel(Parcel in) {
            return new State(in);
        }

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

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

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

    }

    // ... getters and setters
}

这还缺少什么吗?

1 个答案:

答案 0 :(得分:0)

我自己解决了这个问题

以下链接介绍了将ParcelableObject添加到ParcelableObject中的方法。 感谢此链接https://guides.codepath.com/android/using-parcelable

这就是名为“ writeToParcel”的方法的内容

        out.writeString(title);
        out.writeParcelable(from, flags);

如您所见,添加Parcelable Object时,您必须传递“ flags”作为参数。

然后,当您阅读包裹时

        title= in.readString();
        from = in.readParcelable(Person.class.getClassLoader());

您可以阅读包裹以使用这种方式。和注意!您必须匹配您编写的索引。

我希望此解决方案可以帮助其他人

相关问题