[英]how to parcel Object type in Parcelable class in Java
How this class implements parcelable right.这个类如何实现可分割的权利。 i cant do parcel Object type.String, Double,Integer,.. variables types sets to the Object type.我不能做包裹对象类型。字符串,双,整数,..变量类型设置为对象类型。
public class MyClass implements Parcelable {
public String Name;
public Object Value; //variables type to set
protected MyClass(Parcel in) {
Name = in.readString();
//Value = in.?
}
public static final Creator<MyClass> CREATOR = new Creator<MyClass>() {
@Override
public MyClass createFromParcel(Parcel in) {
return new MyClass(in);
}
@Override
public MyClass[] newArray(int size) {
return new MyClass[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(Name);
//dest.
}
}
Probably I am too late but this might help someone else looking for same.可能我为时已晚,但这可能会帮助其他人寻找相同的东西。
Since the Object class does not implement Parcelable, a workaround is needed.由于 Object 类没有实现 Parcelable,因此需要一种解决方法。 A way which i got through this obstacle was by using GSON and serializing and de-serializing to String and from String.我克服这个障碍的一种方法是使用 GSON 并将序列化和反序列化为字符串和从字符串。
For eg:例如:
public class MyClass implements Parcelable {
public String Name;
public Object Value; //variables type to set
protected MyClass(Parcel in) {
Name = in.readString();
Value = new Gson().fromJson(in.readString(), Object.class);
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(Name);
dest.writeString(new Gson().toJson(Value));
}
}
The Parcel
documentation is quite explicit about what you can do, here is some idea. Parcel
文档非常明确地说明了您可以做什么,这里有一些想法。
You have the methods writeParcelable
to do that, but you can't parcel an Object
because Object
doesn't implement Parcelable
.你有方法writeParcelable
来做到这一点,但你不能打包一个Object
因为Object
没有实现Parcelable
。
You need to define a class
that implements Parcelable
for your value
.您需要定义一个为您的value
实现Parcelable
的class
。
public class MyClass implements Parcelable {
public String name;
public ParcelableValue value; //variables type to set
...
}
public class ParcelableValue implements Parcelable {
...
}
For a complete implementation, see Write a sub class of Parcelable to another Parcel完整的实现见将 Parcelable 的子类写到另一个 Parcel
You also have writeValue
but this still have some condition :你也有writeValue
但这仍然有一些条件:
For the complete list, see the doc of the method有关完整列表,请参阅该方法的文档
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.