Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RecyclerView notifyDataSetChanged scrolls to top position

Tags:

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?

like image 395
Mohamed Hatem Abdu Avatar asked Mar 11 '15 17:03

Mohamed Hatem Abdu


People also ask

How do I stop refreshing RecyclerView data scroll to top position android?

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.

What does notifyDataSetChanged do in RecyclerView?

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.

How do I save and restore the scroll position and state of a RecyclerView Android?

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.

Is RecyclerView scrollable?

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 .


2 Answers

If your RecyclerView list item parent has "wrap_content" property, Recyclerview calculates the heights again and scrolls top.

There are two solutions:

  1. Set your height a constant value like this: layout_height="100dp"
  2. Use StaggeredGridLayoutManager like this:

    mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL));

The second solution is more efficient and I suggest this one

like image 53
serefakyuz Avatar answered Sep 18 '22 09:09

serefakyuz


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.  
like image 22
user3354265 Avatar answered Sep 20 '22 09:09

user3354265