I had the exact same problem - for me when my LiveData<List<Item>>
which my recyclerview
was displaying updated in such a way that the first item changed positions, it would always scroll to the new position of that item (but not if any other item other than the first one was moved). I found a relatively simple solution. In the fragment
with the recylcerview
which displays your LiveData
, you presumably have code something like this:
myViewModel.getAllItems().observe(getViewLifeCycleOwner(), items -> {
myAdapter.setItems(items);
});
To stop it from scrolling when the first item is moved, simply add these two lines either side of the setItems()
method:
myViewModel.getAllItems().observe(getViewLifeCycleOwner(), items -> {
Parcelable recyclerViewState = myRecyclerView.getLayoutManager().onSaveInstanceState();
adapter.setItems(slItems);
myRecyclerView.getLayoutManager().onRestoreInstanceState(recyclerViewState);
});
This seems to restore the original scroll position if it was going to change it, making the UI stay at whatever scroll position it was at before the change occurred without any perceptible movement.