2015-08-08 49 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