从 Parcelable 类读取和写入 java.util.Date
我正在使用 Parcelable 类。如何读取和写入对象到该类或从该类写入对象?java.util.Date
我正在使用 Parcelable 类。如何读取和写入对象到该类或从该类写入对象?java.util.Date
在“日期”可序列化的情况下使用写入可序列化。(但不是一个好主意。请参阅下面的另一种更好的方法)
@Override
public void writeToParcel(Parcel out, int flags) {
// Write object
out.writeSerializable(date_object);
}
private void readFromParcel(Parcel in) {
// Read object
date_object = (java.util.Date) in.readSerializable();
}
但是序列化操作会消耗很多性能。如何克服这一点?
因此,更好的用法是在写入时将日期转换为 Long,并读取 Long 并传递给 Date 构造函数以获取 Date。请参阅下面的代码
@Override
public void writeToParcel(Parcel out, int flags) {
// Write long value of Date
out.writeLong(date_object.getTime());
}
private void readFromParcel(Parcel in) {
// Read Long value and convert to date
date_object = new Date(in.readLong());
}
在 Kotlin 中,我们可以为 Parcel 创建扩展 - 最简单的解决方案。
fun Parcel.writeDate(date: Date?) {
writeLong(date?.time ?: -1)
}
fun Parcel.readDate(): Date? {
val long = readLong()
return if (long != -1L) Date(long) else null
}
并使用它
parcel.writeDate(date)
parcel.readDate()