Android Studio 優秀插件: Parcelable Code Generator
這裏假設我們已經會使用 Parcelable 序列化一個對象了~~
那麽大家會發現 Parcelable 使用起來有些復雜,因為我們要自己復寫 幾個方法,而且當類的屬性比較多的時候,我們就會難受了,又要註意不寫錯屬性名,又要註意寫對屬性的類型,又要花不少的時間做重復的事情。
那麽因為 Parcelable 有使用它的優勢,我們又不能放棄,那該怎麽辦麽?
Android Studio 提供給了我們 一個插件用來簡化 給一個類 實現 Parcelable 接口的流程。
-----------------------------------------------------------------------------
現在學習下如何使用這個插件:
1、Android Studio 打開一個項目,點擊左上角 File -->Settings... 進行設置
2、選擇插件Plugins , 搜索Parcel,如果你沒有下載過這個插件,那麽搜索框下面會顯示“Nothing to show.Click Browse to....”
3、那就點擊藍色字體的 Browse 吧 ,這個時候會出現如下圖的界面,我們只需要在左邊選中arcel然後點擊右面 綠色按鈕 "Install plugin" 就可以了
4、完成了上面三個步驟,就可以使用Parcelable Code Generator插件了
怎麽用呢,
(1)創建一個類文件,類名是看你需求自定義寫的,添加上你需要的屬性
(2)快捷鍵 alt+insert ,會出現如下選擇框,選擇Parcelable 即可
然後我們就看到代碼,是不是比我們手動寫要快的許多
public class People implements Parcelable { private int id; private String url; private int width; private int height; private int likeCount; private String description; private int time; private int replyCount; private int floorCount; private int likeUserCount; private int age; private String name; private String school; private int type; private String sax; private int userid; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(this.id); dest.writeString(this.url); dest.writeInt(this.width); dest.writeInt(this.height); dest.writeInt(this.likeCount); dest.writeString(this.description); dest.writeInt(this.time); dest.writeInt(this.replyCount); dest.writeInt(this.floorCount); dest.writeInt(this.likeUserCount); dest.writeInt(this.age); dest.writeString(this.name); dest.writeString(this.school); dest.writeInt(this.type); dest.writeString(this.sax); dest.writeInt(this.userid); } public People() { } protected People(Parcel in) { this.id = in.readInt(); this.url = in.readString(); this.width = in.readInt(); this.height = in.readInt(); this.likeCount = in.readInt(); this.description = in.readString(); this.time = in.readInt(); this.replyCount = in.readInt(); this.floorCount = in.readInt(); this.likeUserCount = in.readInt(); this.age = in.readInt(); this.name = in.readString(); this.school = in.readString(); this.type = in.readInt(); this.sax = in.readString(); this.userid = in.readInt(); } public static final Parcelable.Creator<People> CREATOR = new Parcelable.Creator<People>() { public People createFromParcel(Parcel source) { return new People(source); } public People[] newArray(int size) { return new People[size]; } }; }
Android Studio 優秀插件: Parcelable Code Generator