gpt4 book ai didi

java - 如何使用 ArrayList 正确实现 Parcelable?

转载 作者:IT老高 更新时间:2023-10-28 11:49:11 28 4
gpt4 key购买 nike

我在上课时遇到问题 Parcelable .问题是,我正在尝试将类(class)中的成员写入包裹,该成员是 ArrayList<Parcelable>。目的。 ArrayListSerializable ,并且列表中的对象( 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];
}
};

//...
}

我已经标记了两个点“//help here”,以了解如何正确写入包裹以及如何重建包裹。如果 ZigBeeDevParcelable (经过适当测试),我该如何正确执行此操作?

最佳答案

你几乎明白了!

你只需要这样做:

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);
}

就是这样!

对于你的整数列表,你也可以这样做:

out.writeList(_lqis);
_lqis = new ArrayList<>();
in.readList(_lqis Integer.class.getClassLoader());

它应该可以工作。

关于java - 如何使用 ArrayList<Parcelable> 正确实现 Parcelable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7042272/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com