How to remain at a scroll position in RecyclerView after adding items at its first index and call notifydatasetchange
Asked Answered
I

1

12

I am using a RecyclerView, I add items before the first item, the scroll position moves up to the newly first item added. How can I maintain my scroll position after adding new items at its first index and call notifydatasetchange() ?

this is what i do in my adapter

    mCurrentFragment.items.addAll(0, createLineItems(dataArrayList));

    notifyDataSetChanged();

Any suggestions ?

Ison answered 8/10, 2015 at 9:54 Comment(1)
you can calculate it from the ammount of items you inserted and set scroll value manuallyProlocutor
N
20

There are two options:

  1. Use the more sophisticated versions of notify

    List newData = createLineItems(dataArrayList);
    mCurrentFragment.items.addAll(0, newData);
    notifyItemRangeInserted(0, newData.size());
    
  2. Use stable IDs. On your adapter override public long getItemId (int position) to make it return MEANINGFUL values and call setHasStableIds(true); on it.

Newmarket answered 8/10, 2015 at 10:5 Comment(3)
@Newmarket What do you mean by MEANINGFUL? does it mean a unique id related to each item?Calycle
@HamzehSoboh I meant exactly that. If your IDs are just the position (for example) it won't work. It must be (for example) the user ID, or the photo ID, so when the views position changes the ID remains bounded to the dataNewmarket
It worked on notifyItemRangeInserted but not setHasStableIds although getItemId was returning getTime() for that item's date, which is unique.Calycle

© 2022 - 2024 — McMap. All rights reserved.