我习惯在我从来没有需要做一个模型parcelable这样的概念对我来说并不很清楚的ios开发。 我有一个类“游戏”,如:何时在android中使用parcelable?
//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 _questList是不可parcelable游戏。
任务是一个抽象类,所以它不能执行。
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自定义对象的数组列表传递自定义对象。
我建议你使用的是Android Parcerable发电机: https://github.com/mcharmas/android-parcelable-intellij-plugin – dominik4142
@ dominik4142是parcelable只可能的方式? –
对此有几种方法。最简单:您可以将这些数据存储在应用程序单例中,该单例通过所有应用程序生命保存其状态,或将其存储在数据库中,并在活动之间传递仅某种标识符。不推荐在活动中传递丰富的对象,因为它会使屏幕旋转,屏幕之间的距离真的很慢。 – dominik4142