How can I make my custom objects Parcelable?

后端 未结 11 2581
旧巷少年郎
旧巷少年郎 2020-11-21 07:40

I\'m trying to make my objects Parcelable. However, I have custom objects and those objects have ArrayList attributes of other custom objects I have made.

11条回答
  •  一个人的身影
    2020-11-21 08:20

    Now you can use Parceler library to convert your any custom class in parcelable. Just annotate your POJO class with @Parcel. e.g.

        @Parcel
        public class Example {
        String name;
        int id;
    
        public Example() {}
    
        public Example(int id, String name) {
            this.id = id;
            this.name = name;
        }
    
        public String getName() { return name; }
    
        public int getId() { return id; }
    }
    

    you can create an object of Example class and wrap through Parcels and send as a bundle through intent. e.g

    Bundle bundle = new Bundle();
    bundle.putParcelable("example", Parcels.wrap(example));
    

    Now to get Custom Class object just use

    Example example = Parcels.unwrap(getIntent().getParcelableExtra("example"));
    

提交回复
热议问题