1

在我打包我的 Parcelable 对象并想要返回它之后,变量的值都是 0.0!任何想法为什么?

这是我的 Parcelable 类:

public class ParcelData implements Parcelable {

public byte mapIsSelected; 
public byte carIsSelected;
public byte gameIsPaused;
public float positionX ;
public float positionY ;
public float angle;
public int whichMap; 
public int whichCar;



public ParcelData(byte mapIsSelected, byte carIsSelected, byte gameIsPaused, float positionX, float positionY, float angle, int whichMap, int whichCar){


    this.mapIsSelected = mapIsSelected;
    this.carIsSelected = carIsSelected;
    this.gameIsPaused = gameIsPaused;
    this.positionX = positionX;
    this.positionY = positionY;
    this.angle = angle;
    this.whichCar = whichCar;
    this.whichMap = whichMap;
}


public int describeContents() {

    return 0;
}



public void writeToParcel(Parcel dest, int flags) {

    dest.writeByte(mapIsSelected);
    dest.writeByte(carIsSelected);
    dest.writeByte(gameIsPaused);
    dest.writeFloat(positionX);
    dest.writeFloat(positionY);
    dest.writeFloat(angle);
    dest.writeInt(whichCar);
    dest.writeInt(whichMap);

}


private ParcelData(Parcel in) {

    mapIsSelected = in.readByte();
    carIsSelected = in.readByte();
    gameIsPaused = in.readByte();
    positionX = in.readFloat();
    positionY = in.readFloat();
    angle = in.readFloat();
    whichMap = in.readInt();
    whichCar = in.readInt();
}




 public static final Parcelable.Creator<ParcelData> CREATOR = new Parcelable.Creator<ParcelData>() {

        public ParcelData createFromParcel(Parcel in) {
            return new ParcelData(in);
        }

        public ParcelData[] newArray(int size) {
            // TODO Auto-generated method stub
            return new ParcelData[size];
        }
    };
}

以下是我创建 Parcel 并返回 Parcelable 的方法:

data = new ParcelData((byte)1, (byte)1, (byte)1, 4.0f, 4.0f, 4.0f, 2, 2);
final Parcel parcelData  = Parcel.obtain();
data.writeToParcel(parcelData, 0);

recievedData = ParcelData.CREATOR.createFromParcel(parcelData); 
Log.d ("test", "test: "+ recievedData.positionY);  // always 0.0 ?!?!!?

谢谢

4

1 回答 1

2

好的,我终于有了解决方案:)

在我使用 ParcelData.CREATOR.createFromParcel 之前,我需要将 Parcel 的数据位置设置回 0

data = new ParcelData((byte)1, (byte)1, (byte)1, 4.0f, 4.0f, 4.0f, 2, 2);
final Parcel parcelData  = Parcel.obtain();
data.writeToParcel(parcelData, 0);

parcelData.setDataPosition(0) //<----- Solution

recievedData = ParcelData.CREATOR.createFromParcel(parcelData);
于 2013-01-03T20:55:41.397 回答