簡體   English   中英

什么時候在android中使用parcelable?

[英]When to use parcelable in android?

我習慣於在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;
    }
}

我想開始一個活動,並以我的意圖將游戲對象傳遞給活動,但事實證明,默認情況下你不能傳遞自定義對象,但它們需要是可以分配的。 所以我添加了:

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游戲。

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,我是否必須將它添加到我想傳遞的每個自定義對象(即使在另一個自定義對象中)? 我無法想象他們沒有更容易的東西來傳遞帶有自定義對象數組列表的自定義對象。

正如您已經發現的,如果您想通過Intent發送自己的數據,您需要使其成為可能。 在Android上,建議使用Parcelable 您可以自己實現此界面,也可以使用ParcelerParcelable Please等現有工具。 注意:這些工具有一些限制因此請確保您了解它們,因為有時手動實現Parcelable可能更便宜,而不是編寫代碼來處理它。

只有可能的方式可以包容

不可以。您可以使用Serializable (也可以使用Parcel),但Parcelable可以用於Android,因為它更快,而且它是在平台級別上完成的。

我們假設Parcelable類似於Optimized Serializable,專為Android設計 ,Google建議使用Parcelable over Serializable。 Android操作系統使用Parcelable iteself(例如:SavedState用於查看)。 手動實現Parcelable有點痛苦,所以有一些有用的解決方案:

  • Android Parcerable Generator。 IntelliJ插件,為您的數據類實現Parcelable東西(添加構造函數, CREATOR內部類,實現方法等)。 你可以在這里得到它。 在此輸入圖像描述

  • Parceler。 基於注釋的代碼生成框架。 您必須為數據類和一些輔助方法使用@Parcel注釋。 更多信息在這里 在此輸入圖像描述

  • Parcelable請。 基於注釋的代碼生成框架隨IntelliJ插件一起提供。 我不建議使用它,因為它沒有維持1年。

我個人使用第一個解決方案,因為它快速,簡單,無需弄亂注釋和變通方法。

您可能想閱讀這篇文章

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM