Ornolfr / RatingView

Simple android widget that can replace standard inconvenient RatingBar in your app.
Apache License 2.0
60 stars 15 forks source link

RatingView does not save state on view recreation #3

Closed egidijusk closed 8 years ago

egidijusk commented 8 years ago

First of all thanks for this great widget because default RatingBar widget really sucks. This one is a good replacement. There's one issue, though. If you change rating and rotate the screen then RatingView is recreated but previously set rating is not reset. It resets to default. I have code that solves this problem. Consider adding it to the RatingView class.

@Override
protected Parcelable onSaveInstanceState() {
    Parcelable superState = super.onSaveInstanceState();
    SavedState savedState = new SavedState(superState);
    savedState.mRating = mRating;
    return savedState;
}

@Override
protected void onRestoreInstanceState(Parcelable state) {
    if (state instanceof SavedState) {
        SavedState savedState = (SavedState) state;
        super.onRestoreInstanceState(savedState.getSuperState());
        mRating = savedState.mRating;
    } else {
        super.onRestoreInstanceState(state);
    }
}

static class SavedState extends BaseSavedState {

    float mRating;

    SavedState(Parcelable superState) {
        super(superState);
    }

    private SavedState(Parcel in) {
        super(in);
        this.mRating = in.readFloat();
    }

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

    public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() {
                public SavedState createFromParcel(Parcel in) {
                    return new SavedState(in);
                }

                public SavedState[] newArray(int size) {
                    return new SavedState[size];
                }
            };
}
Ornolfr commented 8 years ago

@egidijusk Thank you for your contribution, your code works well. I added saving mIsIndicator value as well. That's needed improvement.