RecyclerView notifyDataSetChanged scrolls to top position

前端 未结 8 2009
北海茫月
北海茫月 2020-12-11 00:11

when calling notifyDataSetChanged on RecyclerView it doesn\'t retain the scroll position and scrolls to top, is there any solution to retain it\'s

相关标签:
8条回答
  • 2020-12-11 00:50

    You can use swapAdapter() and after call notifyDataSetChange(). This works for me.

    0 讨论(0)
  • 2020-12-11 00:59

    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

    0 讨论(0)
  • 2020-12-11 00:59

    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. 
    
    0 讨论(0)
  • 2020-12-11 01:02

    You can't scroll to position without having set the adapter first. Set your adapter first, even if your list is empty. Update your list when you get the data. Then call adapter.notifydatasetchanged() method. You can then scroll to the last position. Let me know if this answers your question or if I have to put an answer – mmmcho

    0 讨论(0)
  • 2020-12-11 01:10

    As I am guessing, what you are doing is resetting the adapter to the RecyclerView and then calling notifyDataSetChanged().

    You need to pass only the dataList to the adapter by passing dataList in adapter method like adapter update(dataList). And in this method you can assign this list to adapter list like;

    public void update(ArrayList<Hashmap<String,String> list){
      this.mList = list;
    }
    
    0 讨论(0)
  • 2020-12-11 01:10

    In my case, the recyclerview was paginated. Every time it reaches the end and loads/inserts item using notifyItemInserted, the recyclerView used to scroll. So following worked for me:

    recycler_view.stopScroll();

    As stated in the doc:

    Stop any current scroll in progress, such as one started by smoothScrollBy(int, int), fling(int, int) or a touch-initiated fling.

    0 讨论(0)
提交回复
热议问题