Created
February 23, 2017 23:01
-
-
Save hector6872/6b7d9e0889a96e58b3aacaf68d7e4cf3 to your computer and use it in GitHub Desktop.
Custom Viewgroup: onSaveInstanceState - onRestoreInstanceState http://trickyandroid.com/saving-android-view-state-correctly/
This file contains hidden or 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
public class CustomLayout extends LinearLayout { | |
@SuppressWarnings("unchecked") @Override public Parcelable onSaveInstanceState() { | |
Parcelable saveInstanceState = super.onSaveInstanceState(); | |
SavedState savedState = new SavedState(saveInstanceState); | |
savedState.childrenStates = new SparseArray(); | |
for (int i = 0; i < getChildCount(); i++) { | |
getChildAt(i).saveHierarchyState(savedState.childrenStates); | |
} | |
return savedState; | |
} | |
@SuppressWarnings("unchecked") @Override public void onRestoreInstanceState(Parcelable state) { | |
SavedState savedState = (SavedState) state; | |
super.onRestoreInstanceState(savedState.getSuperState()); | |
for (int i = 0; i < getChildCount(); i++) { | |
getChildAt(i).restoreHierarchyState(savedState.childrenStates); | |
} | |
} | |
@Override protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { | |
dispatchFreezeSelfOnly(container); | |
} | |
@Override protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { | |
dispatchThawSelfOnly(container); | |
} | |
private static class SavedState extends BaseSavedState { | |
private SparseArray childrenStates; | |
SavedState(Parcelable superState) { | |
super(superState); | |
} | |
private SavedState(Parcel in, ClassLoader classLoader) { | |
super(in); | |
childrenStates = in.readSparseArray(classLoader); | |
} | |
@SuppressWarnings("unchecked") @Override public void writeToParcel(Parcel out, int flags) { | |
super.writeToParcel(out, flags); | |
out.writeSparseArray(childrenStates); | |
} | |
public static final ClassLoaderCreator<SavedState> CREATOR = new ClassLoaderCreator<SavedState>() { | |
@Override public SavedState createFromParcel(Parcel source, ClassLoader loader) { | |
return new SavedState(source, loader); | |
} | |
@Override public SavedState createFromParcel(Parcel source) { | |
return createFromParcel(null); | |
} | |
public SavedState[] newArray(int size) { | |
return new SavedState[size]; | |
} | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For those who use IcePick, you can use this. This does the same thing as above but lil less ceremony