我试着让我的对象可打包。但是,我有自定义对象,这些对象具有我所做的其他自定义对象的ArrayList属性。
最好的方法是什么?
我试着让我的对象可打包。但是,我有自定义对象,这些对象具有我所做的其他自定义对象的ArrayList属性。
最好的方法是什么?
当前回答
现在,您可以使用Parceler库将任何自定义类转换为parcelable。只需用@Parcel注释POJO类。 如。
@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; }
}
你可以创建一个Example类的对象,并通过包裹进行包装,并通过intent将其作为一个bundle发送。如
Bundle bundle = new Bundle();
bundle.putParcelable("example", Parcels.wrap(example));
现在要获得自定义类对象只需使用
Example example = Parcels.unwrap(getIntent().getParcelableExtra("example"));
其他回答
1. 导入Android Parcelable代码生成器
2. 创建类
public class Sample {
int id;
String name;
}
3.从菜单生成> Parcelable
完成了。
我找到了最简单的方法来创建Parcelable类
IntelliJ IDEA和Android Studio有这样的插件:
★Android Parcelable代码生成器(Apache License 2.0) 汽车包裹(麻省理工学院许可证) SerializableParcelable Generator (MIT许可证) 可打包代码生成器(适用于Kotlin) (Apache许可证2.0)
这些插件基于类中的字段生成Android Parcelable样板代码。
在Android Studio中创建没有插件的Parcelable类
在你的类中实现Parcelable,然后把光标放在“implements Parcelable”上,然后按Alt+Enter并选择添加Parcelable实现(见图片)。就是这样。
将: bundle.putSerializable(“关键”,(序列化)对象);
得到: List<Object> obj = (List<Object>)((Serializable)bundle.getSerializable("key"));