从Parcelable类读写java.util.Date [英] Reading and writing java.util.Date from Parcelable class
本文介绍了从Parcelable类读写java.util.Date的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用Parcelable类.如何在此类中读写 java.util.Date
对象?
I'm working with Parcelable class. How can I read and write java.util.Date
object to and from this class?
推荐答案
Use writeSerializable where Date is Serializable. (But not a good idea. See below for another better way)
@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();
}
但是序列化操作会消耗很多性能.如何克服这个吗?
But Serializing operations consume much performance. How can overcome this?
所以更好的用法是在编写时将日期转换为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());
}
这篇关于从Parcelable类读写java.util.Date的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文