2015-08-08 50 views
4

我习惯在我从来没有需要做一个模型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自定义对象的数组列表传递自定义对象。

+0

我建议你使用的是Android Parcerable发电机: https://github.com/mcharmas/android-parcelable-intellij-plugin – dominik4142

+0

@ dominik4142是parcelable只可能的方式? –

+0

对此有几种方法。最简单:您可以将这些数据存储在应用程序单例中,该单例通过所有应用程序生命保存其状态,或将其存储在数据库中,并在活动之间传递仅某种标识符。不推荐在活动中传递丰富的对象,因为它会使屏幕旋转,屏幕之间的距离真的很慢。 – dominik4142

回答

1

,如果你想通过你需要使它能够意图发送自己的数据正如你已经发现了。在Android上,建议使用Parcelable。您可以自己实现此接口或使用现有的工具,如ParcelerParcelable Please注:这些工具附带了一些限制,确保你知道他们因为有时它可能会更便宜来实现手动,而不需要编写代码Parcelable围绕解决它。

是parcelable只可能的方式

号您可以使用Serializable(也包裹),但Parcelable是走在Android,因为它是更快的方式,这是它是如何做的平台级别。

1

假设Parcelable类似于优化的Serializable,专为Android设计,Google建议使用Parcelable over Serializable。 Android操作系统使用Parcelable iteself(例如:SavedState for Views)。手工实现Parcelable是有点痛苦的,所以有一些有用的解决方案:

  • 的Android Parcerable发电机。 的IntelliJ插件,可以实现Parcelable东西给你(增加构造,CREATOR内部类,实现方法等),为您的数据类。你可以得到它hereenter image description here

  • Parceler。 基于注解的代码生成框架。您必须为您的数据类使用@Parcel注释,以及一些辅助方法。更多信息hereenter image description here

  • Parcelable请。 基于注释的代码生成框架与IntelliJ插件一起提供。我不会推荐使用它,因为它不会保留1年。

我个人使用1解决方案,因为它的快速,简便,不需要乱七八糟的注释和解决方法。

您可能想要阅读这个article