Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
CoordinatorLayout properly restoring the Behavior states on API < 13 by avoiding null ClassLoaders
package be.digitalia.common.widgets;
import android.content.Context;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.os.ParcelableCompat;
import android.support.v4.os.ParcelableCompatCreatorCallbacks;
import android.util.AttributeSet;
/**
* CoordinatorLayout properly restoring the Behavior states on API < 13 by avoiding null ClassLoaders.
*
* @author Christophe Beyls
*/
public class SafeCoordinatorLayout extends CoordinatorLayout {
public SafeCoordinatorLayout(Context context) {
super(context);
}
public SafeCoordinatorLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SafeCoordinatorLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected Parcelable onSaveInstanceState() {
final Parcelable superState = super.onSaveInstanceState();
if (superState instanceof CoordinatorLayout.SavedState) {
return new SavedState((CoordinatorLayout.SavedState) superState);
}
return superState;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
if (state instanceof SavedState) {
final SavedState ss = (SavedState) state;
super.onRestoreInstanceState(ss.wrappedState);
} else {
super.onRestoreInstanceState(state);
}
}
protected static class SavedState implements Parcelable {
final CoordinatorLayout.SavedState wrappedState;
public SavedState(Parcel source, ClassLoader loader) {
if (loader == null) {
loader = CoordinatorLayout.class.getClassLoader();
}
wrappedState = new CoordinatorLayout.SavedState(source, loader);
}
public SavedState(CoordinatorLayout.SavedState state) {
wrappedState = state;
}
@Override
public int describeContents() {
return wrappedState.describeContents();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
wrappedState.writeToParcel(dest, flags);
}
public static final Parcelable.Creator<SavedState> CREATOR
= ParcelableCompat.newCreator(new ParcelableCompatCreatorCallbacks<SavedState>() {
@Override
public SavedState createFromParcel(Parcel in, ClassLoader loader) {
return new SavedState(in, loader);
}
@Override
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