在我打包了我的可打包对象并想将其返回时,变量的值都为0.0!知道为什么吗?

这是我的包裹类:

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];
        }
    };
}


这是我创建包裹的方式,然后返回到包裹:

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 ?!?!!?


谢谢

最佳答案

好的,最后我有了解决方案:)

在使用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);

关于android - 在宗地之后,宗地的变量的值始终为0.0,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14113831/

10-09 12:54