我正在使用Android应用并尝试在屏幕旋转时保存数据。我将这些数据放在一个名为mCheatedResults的数组中。这是一组自定义对象,它们将布尔数据和int配对。我为自定义对象创建类的代码是:
private class Pair implements Parcelable{
private int mIndex;
private boolean mCheated;
public Pair(int mIndex, boolean mCheated){
this.mIndex=mIndex;
this.mCheated=mCheated;
}
public Pair(Parcel in){
mIndex= in.readInt();
mCheated=in.readByte()!=0;
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags){
out.writeInt(mIndex);
out.writeByte((byte)(mCheated ? 1:0));
}
public final Parcelable.Creator<Pair> CREATOR = new Parcelable.Creator<Pair>(){
public Pair createFromParcel(Parcel in){
return new Pair(in);
}
public Pair[] newArray(int size) {
return new Pair[size];
}
};
public int getIndex(){
return mIndex;
}
public boolean didCheat(){
return mCheated;
}
public void setBoolean(boolean mCheated) {
this.mCheated = mCheated;
}
}
我试图用来将Pair对象数组附加到bundle的代码如下:
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
Log.i(TAG, "onSaveInstanceState");
savedInstanceState.putInt(KEY_INDEX, mCurrentIndex);
savedInstanceState.putParcelableArray(QUESTIONS_CHEATED, mCheatedResults);
}
我发现文档表明这可行,但似乎没有用。有什么建议吗?
答案 0 :(得分:0)
直接从捆绑中读取Parcelable数组将不起作用。例如:
Pair[] pairs = savedInstanceState.getParcelableArray(QUESTIONS_CHEATED);
这就是我阅读Parcelable数组的方法:
Parcelable[] parcelables = savedInstanceState.getParcelableArray(QUESTIONS_CHEATED);
Pair[] pairs = new Pair[parcelables.length];
for(int i = 0; i < parcelables.length; i++) {
pairs[i] = (Pair) parcelable[i];
}
如果有人知道更好的方式,我想知道。