android-fragmentsandroid-recyclerviewmaintainscrollpositionon

Restoring RecyclerView scroll position within a Fragment


There a more than enough questions on SO about this, but no method I try seems to work. All I am trying to do is restore the "scroll position" of a RecyclerView that is nested within a Fragment. For example, when a new fragment is opened (using .replace()) and then closed, the original fragment shows the same screen that it had before the new fragment was opened ie. the scroll position of the RecyclerView is restored; however, this is not what is happening. I am using Bottom Navigation to open fragments. Below is the method I am using, which I would have thought would work seeing as it is the most common answer to this problem.

private Parcelable recLayoutState;
private Bundle recBundle;
private static String LIST_STATE = "LIST_STATE";

@Override
public void onPause(){
    super.onPause();

    recLayoutState = homeRecyclerLayoutManager.onSaveInstanceState();
    recBundle = new Bundle();
    recBundle.putParcelable(LIST_STATE,recLayoutState);
}

@Override
public void onResume(){
    super.onResume();

    if (recBundle != null){
        recLayoutState = recBundle.getParcelable(LIST_STATE);
        homeRecyclerLayoutManager.onRestoreInstanceState(recLayoutState);
    }


}

This code is in the fragment.java file.

When I open a new fragment then go back to this one, the RecyclerView is set to the top and not at the previous scroll position.

Any help appreciated and I'm happy to provide more information if needed! Cheers!


Solution

  • I solved my problem by "hiding" fragments when I changed tabs. This link was very helpful! This way the fragment doesn't get destroyed and the life cycle doesn't restart.