when calling notifyDataSetChanged
on RecyclerView
it doesn't retain the scroll position and scrolls to top, is there any solution to retain it's scroll position?
Just set your LayoutManager and adapter for the first time. Make a setDataList method in your adapter class. And set your updated list to adapter list. And then every time of calling API set that list to setDataList and call adapter.
notifyDataSetChanged. Notify any registered observers that the data set has changed. There are two different classes of data change events, item changes and structural changes. Item changes are when a single item has its data updated but no positional changes have occurred.
Restoring scroll position the official way RecyclerView offers a new API to let the Adapter block layout restoration until it is ready. The recyclerview:1.2. 0-alpha02 solution allows you to set a state restoration policy via the StateRestorationPolicy enum. This has 3 options.
To be able to scroll through a vertical list of items that is longer than the screen, you need to add a vertical scrollbar. Inside RecyclerView , add an android:scrollbars attribute set to vertical .
If your RecyclerView list item parent has "wrap_content" property, Recyclerview calculates the heights again and scrolls top.
There are two solutions:
layout_height="100dp"
Use StaggeredGridLayoutManager like this:
mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL));
The second solution is more efficient and I suggest this one
Not sure if this solves your problem but I was having the same issue and it was because I was calling setAdapter after notify. So, not calling setAdapter after notify solved the problem.
mAdapter.notifyItemRangeInserted(mAdapter.getItemCount(), list.size() - 1); recyclerView.setAdapter(); // remove this line. //Do this only when you're setting the data for the first time or when adapter is null.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With