Implementing a parcelable class requires three simple steps:
1 - Make the class implement Parcelable
2 - Implement a constructor that receives a Parcel object and override writeToParcel method. One importante aspect to take into account at this step is that you have to read from the Parcel object in the same other your write to it.
3 - Create a custom Creator class that will create your Parcelable class. One
Lets do this:
import android.os.Parcel;
import android.os.Parcelable;
public class ParceableString implements Parcelable {
private String string;
...
public ParceableString(Parcel in){
string = in.readString();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(string);
}
@Override
public int describeContents(){
return 0;
}
public static final Parcelable.Creator<ParceableString> CREATOR = new Parcelable.Creator<ParceableString>() {
public ParceableString createFromParcel(Parcel in) {
return new ParceableString(in);
}
public ParceableString[] newArray(int size) {
return new ParceableString[size];
}
};
}
If your object contains other objects you would have to make those objects implement Parceable or persists its attributes as primitive types or other classes that are Parceable.public class MyClass implements Parcelable {
private MyPoint myPoint;
private ParceableClass parceableObject;
public MyClass(Parcel in){
myPoint = new MyPoint(in.readInt(), in.readInt());
parceableObject = new ParceableClass(in);
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(myPoint.x);
dest.writeInt(myPoint.y);
parceableObject.writeToParcel(dest, flags);
}
...
}
https://github.com/CharlesHarley/Example-Android-SavingInstanceState/blob/master/src/com/example/android/savinginstancestate/views/LockCombinationPicker.java
No hay comentarios:
Publicar un comentario