Android Parcelable用法

时间:2015-06-25 23:04:22

标签: android parcelable

我有一个具有以下结构的类:

class Example {
    Integer age;
    String name;
    Collection<Example2>examples;

    class Example2 {
        Integer number;
         Collection<String>strings;
   }
}

如何让这个类实现Parcelable,以便我可以跨活动发送它的对象。

2 个答案:

答案 0 :(得分:1)

最简单的方法是使用@AutoParcel并让它为您处理繁重的工作。

答案 1 :(得分:0)

你应该看一下这个帖子:Android: Making a class parcelable

所以你的课程应该是这样的:

class Example implements Parcelable {
    Integer age;
    String name;
    ArrayList<Example2> examples;

    public Example(Parcel in) {
        examples = new ArrayList<>();
        readFromParcel(in);
    }

   @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(age);
        dest.writeString(name);
        dest.writeList(examples != null ? examples : new ArrayList());
    }

    private void readFromParcel(Parcel in) {
        age = in.readInt();
        name = in.readString();
        in.readList(examples, Example2.class.getClassLoader());
    }

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

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

class Example2 implements Parcelable {
   Integer number;
   ArrayList<String> labels;

   public Example2(Parcel in) {
        labels = new ArrayList<>();
        readFromParcel(in);
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInteger(number);
        dest.writeList(labels != null ? labels : new ArrayList());
    }

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

    private void readFromParcel(Parcel in) {
        number = in.readInteger();
        in.readStringList(labels);
    }

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

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