Android
IntentからIntentにいろいろな値を受け渡ししますね。
自作のクラスのオブジェクトもParcelableというインターフェースを実装することで受け渡しできますが、Enumのクラスだと、一工夫必要です。
Parcelableに受け渡せるようにできるようにするサンプルコードです。
public enum VehicleType implements Parcelable {
FLAT_BODY("FLAT_BODY"),
WING("WING"),
VAN("VAN"),
FREEZER_CAR("FREEZER_CAR"),
POWER_GATE("POWER_GATE");
private final String name;
private VehicleType(String s) {
name = s;
}
public String toString() {
return this.name;
}
public static VehicleType fromString(String vehicle_type_str) {
return stringToEnum.get(vehicle_type_str);
}
private final static EnumMap<VehicleType, Integer> vehicleImageMap;
public static int toIconImage(VehicleType vehicleType){
return vehicleImageMap.get(vehicleType);
}
private static final Map<String, VehicleType> stringToEnum = new HashMap<String, VehicleType>();
static {
stringToEnum.put("1", FLAT_BODY);
stringToEnum.put("2", WING);
stringToEnum.put("3", VAN);
stringToEnum.put("4", FREEZER_CAR);
stringToEnum.put("5", POWER_GATE);
vehicleImageMap = new EnumMap<VehicleType, Integer>(VehicleType.class);
vehicleImageMap.put(VehicleType.FLAT_BODY, R.drawable.icon_car_flat);
vehicleImageMap.put(VehicleType.WING, R.drawable.icon_car_wing);
vehicleImageMap.put(VehicleType.VAN, R.drawable.icon_car_van);
vehicleImageMap.put(VehicleType.FREEZER_CAR, R.drawable.icon_car_freeze);
vehicleImageMap.put(VehicleType.POWER_GATE, R.drawable.icon_power_gate);
}
// 99.9% of the time you can just ignore this
@Override
public int describeContents() {
return 0;
}
// write your object's data to the passed-in Parcel
@Override
public void writeToParcel(Parcel out, int flags) {
out.writeString(name);
}
// this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods
public static final Parcelable.Creator<VehicleType> CREATOR = new Parcelable.Creator<VehicleType>() {
public VehicleType createFromParcel(Parcel in) {
return VehicleType.values()[in.readInt()];
}
public VehicleType[] newArray(int size) {
return new VehicleType[size];
}
};
// example constructor that takes a Parcel and gives you an object populated with it's values
private VehicleType(Parcel in) {
name = in.readString();
}
};
下記を参考にさせて頂きました、ありがとうございます。
http://stackoverflow.com/questions/2836256/passing-enum-or-object-through-an-intent-the-best-solution