gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 10:18:04 25 4
gpt4 key购买 nike

我习惯于在 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;
}
}

我想启动一个 Activity 并按照我的 Intent 将游戏对象传递给该 Activity ,但事实证明默认情况下您不能传递自定义对象,但它们需要是可分割的。所以我添加了:

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());
}

但现在我收到自定义数组列表 _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,我是否必须将它添加到我想要传递的每个自定义对象(即使在另一个自定义对象中)?我无法想象他们没有更容易让 android 传递带有自定义对象数组列表的自定义对象的方法。

最佳答案

正如您已经发现的那样,如果您想通过 Intent 发送自己的数据,您需要使其成为可能。在 Android 上,建议使用 Parcelable。您可以自己实现此接口(interface)或使用现有工具,如 ParcelerParcelable Please . 注意:这些工具有一些限制,因此请确保您了解它们,因为有时手动实现 Parcelable 比编写代码来解决它可能更便宜。

is parcelable to only way possible

没有。您可以使用 Serializable(也可以使用 Parcels),但是 Parcelable 是在 Android 上运行的方式,因为它速度更快,而且它是在平台级别上完成的。

关于java - 什么时候在android中使用parcelable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31895942/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com