-
-
Save amirbakhtiari/bb1faef551084a37d8840633bdbaa5ae to your computer and use it in GitHub Desktop.
Saving state on configuration changes for a custom view.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.operator.android; | |
import android.content.Context; | |
import android.os.Parcel; | |
import android.os.Parcelable; | |
import android.view.View; | |
/** | |
* A custom {@link View} that demonstrates how to save/restore instance state. | |
*/ | |
public class CustomView extends View { | |
private boolean someState; | |
public CustomView(Context context) { | |
super(context); | |
} | |
public boolean isSomeState() { | |
return someState; | |
} | |
public void setSomeState(boolean someState) { | |
this.someState = someState; | |
} | |
@Override protected Parcelable onSaveInstanceState() { | |
final Parcelable superState = super.onSaveInstanceState(); | |
final CustomViewSavedState customViewSavedState = new CustomViewSavedState(superState); | |
customViewSavedState.someState = this.someState; | |
return customViewSavedState; | |
} | |
@Override protected void onRestoreInstanceState(Parcelable state) { | |
final CustomViewSavedState customViewSavedState = (CustomViewSavedState) state; | |
setSomeState(customViewSavedState.someState); | |
super.onRestoreInstanceState(customViewSavedState.getSuperState()); | |
} | |
private static class CustomViewSavedState extends BaseSavedState { | |
boolean someState; | |
public static final Parcelable.Creator<CustomViewSavedState> CREATOR = new Creator<CustomViewSavedState>() { | |
@Override public CustomViewSavedState createFromParcel(Parcel source) { | |
return new CustomViewSavedState(source); | |
} | |
@Override public CustomViewSavedState[] newArray(int size) { | |
return new CustomViewSavedState[size]; | |
} | |
}; | |
public CustomViewSavedState(Parcelable superState) { | |
super(superState); | |
} | |
private CustomViewSavedState(Parcel source) { | |
super(source); | |
someState = source.readInt() == 1; | |
} | |
@Override public void writeToParcel(Parcel out, int flags) { | |
super.writeToParcel(out, flags); | |
out.writeInt(someState ? 1 : 0); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment