Skip to content

Instantly share code, notes, and snippets.

@premacck
Last active August 22, 2018 07:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save premacck/d172e0d88935609453caa55d8da75911 to your computer and use it in GitHub Desktop.
Save premacck/d172e0d88935609453caa55d8da75911 to your computer and use it in GitHub Desktop.
RecyclerView which saves and restores states on application lifecycle changes.
// TODO: put package information here
import android.content.Context;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
/**
*
* Created by Prem$ on 2/19/2018.
*/
public class StatefulRecyclerView extends RecyclerView {
private static final String SAVED_SUPER_STATE = "super-state";
private static final String SAVED_LAYOUT_MANAGER = "layout-manager-state";
private Parcelable mLayoutManagerSavedState;
public StatefulRecyclerView(Context context) {
super(context);
}
public StatefulRecyclerView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public StatefulRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected Parcelable onSaveInstanceState() {
Bundle bundle = new Bundle();
bundle.putParcelable(SAVED_SUPER_STATE, super.onSaveInstanceState());
bundle.putParcelable(SAVED_LAYOUT_MANAGER, this.getLayoutManager().onSaveInstanceState());
return bundle;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
if (state instanceof Bundle) {
Bundle bundle = (Bundle) state;
mLayoutManagerSavedState = bundle.getParcelable(SAVED_LAYOUT_MANAGER);
state = bundle.getParcelable(SAVED_SUPER_STATE);
}
super.onRestoreInstanceState(state);
}
/**
* Restores scroll position after configuration change.
* <p>
* <b>NOTE:</b> Must be called after adapter has been set.
*/
private void restorePosition() {
if (mLayoutManagerSavedState != null) {
this.getLayoutManager().onRestoreInstanceState(mLayoutManagerSavedState);
mLayoutManagerSavedState = null;
}
}
@Override
public void setAdapter(Adapter adapter) {
super.setAdapter(adapter);
restorePosition();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment