1

我在一个布局中有 4 个自定义复合组件,每个都从 RelativeLayout 扩展。从概念上讲,它们只是带有标题和复选框的列表行。我希望每个组件都保留它自己的检查状态。不幸的是,他们似乎以某种方式共享他们的状态,即在配置更改后,所有四个的检查状态取决于是否仅检查了布局中的最后一个。我做了一些日志记录,发现 onSaveInstanceState 和 onRestoreInstanceState 每个唯一标识的行都被调用两次。

我会很感激任何帮助,这令人困惑

private int NOT_CHECKED = 0;
private int IS_CHECKED = 1;
@Override
protected Parcelable onSaveInstanceState() {
    Parcelable superState = super.onSaveInstanceState();
    SavedState ss = new SavedState(superState);
    ss.checked = mCheckBox.isChecked() ? IS_CHECKED : NOT_CHECKED;
    Log.e("Active", "Out - " + this.getId() + " - " + mCheckBox.isChecked());
    return ss;
} 
@Override
protected void onRestoreInstanceState(Parcelable state) {
    if(!(state instanceof SavedState)) {
        super.onRestoreInstanceState(state);
        return;
    }
    SavedState ss = (SavedState) state;
    super.onRestoreInstanceState(ss.getSuperState());
    mCheckBox.setChecked(ss.checked == IS_CHECKED ? true : false);
    Log.e("Active", "In - " + this.getId() + " - " + mCheckBox.isChecked());
}


private static class SavedState extends BaseSavedState {
private int checked;

SavedState(Parcelable superState) {
    super(superState);
}
private SavedState(Parcel in) {
    super(in);
    this.checked = in.readInt();

}
@Override
public void writeToParcel(Parcel out, int flags) {
    super.writeToParcel(out, flags);

    out.writeInt(this.checked);
}
public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<FilterCheckBoxRow.SavedState>() {

    public SavedState createFromParcel(Parcel in) {
        return new SavedState(in);
    }
    public SavedState[] newArray(int size) {
        return new SavedState[size];
    }

};

}

4

0 回答 0