java parcelable list_java – 什么时候在android中使用parcelable?

我习惯于在ios中开发我永远不需要制作可模仿的模型,所以这个概念对我来说不是很清楚.

我有一个类“游戏”,如:

//removed the method to make it more readable.

public class Game implements Parcelable {

private int _id;

private ArrayList _questList;

private int _numberOfGames;

private String _name;

private Date _startTime;

public Game(String name, ArrayList quests, int id){

_name = name;

_questList = quests;

_numberOfGames = quests.size();

_id = id;

}

}

我想开始一个活动,并以我的意图将游戏对象传递给活动,但事实证明,默认情况下你不能传递自定义对象,但它们需要是可以分配的.所以我添加了:

public static final Parcelable.Creator CREATOR

= new Parcelable.Creator() {

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) 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 _questList不是parcelable游戏.

Quest是一个抽象类,因此无法实现.

public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {

public Game createFromParcel(Parcel source) {

return new Game(source);

}

public Game[] newArray(int size) {

return new Game[size];

}

};

所以我的问题是:我什么时候需要实现parcelable,我是否必须将它添加到我想传递的每个自定义对象(即使在另一个自定义对象中)?我无法想象他们没有更容易的东西来传递带有自定义对象数组列表的自定义对象.

最佳答案 正如您已经发现的,如果您想通过Intent发送自己的数据,您需要使其成为可能.在Android上,建议使用Parcelable.您可以自己实现此接口,也可以使用现有的工具,如

Parceler或

Parcelable Please.注意:这些工具有一些限制,因此请确保您了解它们,因为有时手动实现Parcelable可能更便宜,而不是编写代码来处理它.

is parcelable to only way possible

不可以.您可以使用Serializable(也可以使用Parcel),但Parcelable可以用于Android,因为它更快,而且它是在平台级别上完成的.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值