この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。
Activity間でのモデルのやりとりや、再生成時の復元処理などで利用するParcelableですが、 describeContents(), writeToParcel(), Parcelable.Creator などを実装する必要があるので、結構面倒くさいですね。
そんなときは、Android Studio PluginのAndroid Parcelable code generatorを使うと、上記の実装部分を自動生成してくれるので非常に便利です
プラグインのインストール
[Android Studio] - [Preference] - [Plugins] - [Browse repositories] でparcelableを検索し、インストールします。
あとは、Android Studioを再起動すればインストール完了です。
プラグインを使う
まずは、モデルクラスを作成します。 とりあえずコンストラクタとgetterメソッドを用意しました。
public class MyParcelable {
private long id;
private int count;
private String name;
public MyParcelable(long id, int count, String name) {
this.id = id;
this.count = count;
this.name = name;
}
public long getId() {
return id;
}
public int getCount() {
return count;
}
public String getName() {
return name;
}
}
クラス内でGenerateメニューを開くと、Parcelableが追加されているのでクリックします。
対象変数の選択画面が表示されるので、そのまま[OK]ボタンをクリックすると、Parcelableの実装を自動生成してくれます。
public class MyParcelable implements Parcelable {
private long id;
private int count;
private String name;
public MyParcelable(long id, int count, String name) {
this.id = id;
this.count = count;
this.name = name;
}
public long getId() {
return id;
}
public int getCount() {
return count;
}
public String getName() {
return name;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(this.id);
dest.writeInt(this.count);
dest.writeString(this.name);
}
protected MyParcelable(Parcel in) {
this.id = in.readLong();
this.count = in.readInt();
this.name = in.readString();
}
public static final Parcelable.Creator<MyParcelable> CREATOR = new Parcelable.Creator<MyParcelable>() {
@Override
public MyParcelable createFromParcel(Parcel source) {
return new MyParcelable(source);
}
@Override
public MyParcelable[] newArray(int size) {
return new MyParcelable[size];
}
};
}
おわりに
定形的なコードは、なるべく自動生成できるようになると開発効率が上がるので、こういったプラグインは非常に助かりますね。