我在上课Parcelable
时遇到麻烦。麻烦的是,我正在尝试将包裹中的一个成员写入一个类,该成员是ArrayList<Parcelable>
对象。 ArrayList
是Serializable
,列表中的对象(ZigBeeDev
)是Parcelable
。
以下是相关代码:
package com.gnychis.coexisyst;
import java.util.ArrayList;
import java.util.Iterator;
import android.os.Parcel;
import android.os.Parcelable;
public class ZigBeeNetwork implements Parcelable {
public String _mac; // the source address (of the coordinator?)
public String _pan; // the network address
public int _band; // the channel
ArrayList<Integer> _lqis; // link quality indicators (to all devices?)
ArrayList<ZigBeeDev> _devices; // the devices in the network
public void writeToParcel(Parcel out, int flags) {
out.writeString(_mac);
out.writeString(_pan);
out.writeInt(_band);
out.writeSerializable(_lqis);
out.writeParcelable(_devices, 0); // help here
}
private ZigBeeNetwork(Parcel in) {
_mac = in.readString();
_pan = in.readString();
_band = in.readInt();
_lqis = (ArrayList<Integer>) in.readSerializable();
_devices = in.readParcelable(ZigBeeDev.class.getClassLoader()); // help here
}
public int describeContents() {
return this.hashCode();
}
public static final Parcelable.Creator<ZigBeeNetwork> CREATOR =
new Parcelable.Creator<ZigBeeNetwork>() {
public ZigBeeNetwork createFromParcel(Parcel in) {
return new ZigBeeNetwork(in);
}
public ZigBeeNetwork[] newArray(int size) {
return new ZigBeeNetwork[size];
}
};
//...
}
我在“//帮助这里”标记了两个点,以了解如何正确地写包裹以及如何对其进行重建。如果
ZigBeeDev
是Parcelable
(已正确测试),如何正确执行此操作? 最佳答案
你差点知道了!
您只需要做:
public void writeToParcel(Parcel out, int flags) {
out.writeString(_mac);
out.writeString(_pan);
out.writeInt(_band);
out.writeSerializable(_lqis);
out.writeTypedList(_devices);
}
private ZigBeeNetwork(Parcel in) {
_mac = in.readString();
_pan = in.readString();
_band = in.readInt();
_lqis = (ArrayList<Integer>) in.readSerializable();
in.readTypedList(_devices, ZigBeeDev.CREATOR);
}
就这样!
对于您的Integer列表,您还可以执行以下操作:
out.writeList(_lqis);
_lqis = new ArrayList<>();
in.readList(_lqis Integer.class.getClassLoader());
它应该工作。
关于java - 如何使用ArrayList <Parcelable>正确实现Parcelable?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7042272/