Android Custom view save and restore state

Viewed 3314

I had custom components extended ImageView. Methods onSaveInstanceState and onRestoreInstanceState works correctly, but unfortunately when I click to the view mIsSelectedState = false

How can I solve this problem?

public class CustomImageView extends ImageView {

private boolean mIsSelectedState;
...

public CustomImageView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init(context, attrs, defStyleAttr);
}

private void init(Context context, AttributeSet attrs, int defStyleAttr) {
    setSaveEnabled(true);

    TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.CustomImageView, defStyleAttr, 0);
    ...
    attributes.recycle();

    mPaintImage = new Paint(Paint.ANTI_ALIAS_FLAG);
    ...
}

@Override
public boolean dispatchTouchEvent(MotionEvent event) {
    if (!isClickable()) {
        mIsSelectedState = false;
        return super.onTouchEvent(event);
    }

    ...

    invalidate();
    return super.dispatchTouchEvent(event);
}

...

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

    savedState.mSelected = mIsSelectedState;
    return savedState;
}

@Override
protected void onRestoreInstanceState(Parcelable state) {
    if(!(state instanceof SavedState)) {
        super.onRestoreInstanceState(state);
        return;
    }

    SavedState savedState = (SavedState)state;
    super.onRestoreInstanceState(savedState.getSuperState());
    setSelectedState(savedState.mSelected);
    setBorderColor(mBorderSelectedColor);
}

private void setSelectedState(boolean isSelected) {
    mIsSelectedState = isSelected;
}

...

private static class SavedState extends BaseSavedState {
    boolean mSelected;

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

    private SavedState(Parcel in) {
        super(in);
        mSelected = in.readByte() != 0;
    }

    @Override
    public void writeToParcel(Parcel out, int flags) {
        super.writeToParcel(out, flags);
        out.writeByte((byte) (mSelected ? 1 : 0));
    }

    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];
                }
            };
}
1 Answers
Related