java何时在安卓中使用parcelable?
我习惯于在ios中开发,在那里我永远不需要将模型打包,所以这个概念对我来说不是很清楚。 我有一个类“游戏”,比如:
//removed the method to make it more readable.
public class Game implements Parcelable {
private int _id;
private ArrayList<Quest> _questList;
private int _numberOfGames;
private String _name;
private Date _startTime;
public Game(String name, ArrayList<Quest> quests, int id){
_name = name;
_questList = quests;
_numberOfGames = quests.size();
_id = id;
}
}
我想启动一个活动,并按照我的意图将游戏对象传递给该活动,但结果表明,默认情况下,您无法传递自定义对象,但它们必须是可包裹的。所以我补充说:
public static final Parcelable.Creator<Game> CREATOR
= new Parcelable.Creator<Game>() {
public Game createFromParcel(Parcel in) {
return new Game(in);
}
public Game[] newArray(int size) {
return new Game[size];
}
};
private Game(Parcel in) {
_id = in.readInt();
_questList = (ArrayList<Quest>) in.readSerializable();
_numberOfGames = in.readInt();
_name = in.readString();
_startTime = new Date(in.readLong());
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel out, int flags) {
out.writeInt(_id);
out.writeSerializable(_questList);
out.writeInt(_numberOfGames);
out.writeString(_name);
out.writeLong(_startTime.getTime());
}
但是现在我得到一个警告,定制的arraylist\u questList不是可包裹的游戏
Quest是一个抽象类,因此无法实现
public static final Parcelable.Creator<Game> CREATOR = new Parcelable.Creator<Game>() {
public Game createFromParcel(Parcel source) {
return new Game(source);
}
public Game[] newArray(int size) {
return new Game[size];
}
};
所以我的问题是:什么时候我需要实现parcelable,我是否必须将它添加到我想要传递的每个自定义对象中(即使是在另一个自定义对象中)?我无法想象他们没有什么东西能让安卓更容易地传递带有自定义对象数组列表的自定义对象
# 1 楼答案
正如你已经发现的,如果你想通过Intent发送自己的数据,你需要让它成为可能。在Android上,建议使用
Parcelable
。您可以自己实现这个接口,或者使用Parceler或Parcelable Please等现有工具注意:这些工具有一些局限性,因此请确保您了解它们,因为有时手工实现Parcelable
可能比编写代码更便宜不可以。你可以使用
Serializable
(也可以用于包裹),但是Parcelable
是Android上的一种方式,因为它更快,而且在平台级别上也是如此# 2 楼答案
比如说Parcelable是一种类似于优化序列化的东西,专为Android设计,谷歌建议使用Parcelable而不是Serializable。Android操作系统使用
Parcelable
iteself(例如:视图的SavedState)。手工实现Parcelable
有点痛苦,所以有一些有用的解决方案:Android可分配生成器 IntelliJ插件为您的数据类实现![enter image description here](https://i.stack.imgur.com/N69tgl.png)
Parcelable
东西(添加构造函数,CREATOR内部类,实现方法等)。你可以得到它包裹员 基于注释的代码生成框架。您必须为您的数据类使用![enter image description here](https://i.stack.imgur.com/aOa3Am.png)
@Parcel
注释,以及一些辅助方法。更多信息here。请用包裹 IntelliJ插件附带了基于注释的代码生成框架。我不建议使用它,因为它没有维护一年
就我个人而言,我使用第一种解决方案,因为它快速、简单,而且不需要打乱注释和解决方法
你可能想读一下这个article