Skip to content

Instantly share code, notes, and snippets.

@matthew-carroll
Created July 6, 2019 11:00
Show Gist options
  • Save matthew-carroll/ae0a7872ac47f0e50148d02a395dee72 to your computer and use it in GitHub Desktop.
Save matthew-carroll/ae0a7872ac47f0e50148d02a395dee72 to your computer and use it in GitHub Desktop.
Saving child state in custom ViewGroup with new SparseArray.
@Override
protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
// Create a SparseArray just for us!
SparseArray mySparseArray = new SparseArray(mChildrenCount + 1); // +1 for our ViewGroup's state.
// Repeat the normal logic for this method, but pass our "mySparseArray" instead of "container"
super.dispatchSaveInstanceState(mySparseArray);
final int count = mChildrenCount;
final View[] children = mChildren;
for (int i = 0; i < count; i++) {
View c = children[i];
if ((c.mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED) {
c.dispatchSaveInstanceState(mySparseArray);
}
}
// Put mySparseArray in the container we were given.
container.put(getId(), mySparseArray);
}
@vejei
Copy link

vejei commented Feb 23, 2021

How can you put a SparseArray to the SparseArray whose generic type is Parcelable? The IDE complain that the required type is Parcelable but provided is SparseArray.

The correctly solution should be like this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment