So, I have an EditText on which I have set onEditorActionListener, i.e after the user enters the text and presses enter/search it will fetch the details and populate the recycler view accordingly.
Now in order to save the state on a configuration change I have wrote the following code -
Parcelable stateList;
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//Saving instance of the state in Parcelable stateList
stateList = recyclerView.getLayoutManager().onSaveInstanceState();
outState.putParcelable(RETAIN_STATE, stateList);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
if(savedInstanceState!=null) {
stateList = savedInstanceState.getParcelable(RETAIN_STATE);
recyclerView.getLayoutManager().onRestoreInstanceState(stateList);
}
}
But when I run this, and rotate the screen the recycler view does not restore the state from the stateList parcelable.
I am using MVP, so I'm setting the adapter in the callback of the presenter.
I was able to retain the state when we click on enter/search on the keyboard after the screen was rotated, so I tried this hack in the onRestoreInstanceState(), but I think there should be a better way to go about this.
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
if(savedInstanceState!=null) {
//The hack!
et_search.onEditorAction(EditorInfo.IME_ACTION_SEARCH);
stateList = savedInstanceState.getParcelable(RETAIN_STATE);
recyclerView.getLayoutManager().onRestoreInstanceState(stateList);
}
}
Let me know if there is more information needed. Thanks in advance.