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 ?

eddykordo
  • 607
  • 5
  • 14

1 Answers1

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.

Chad Bingham
  • 32,650
  • 19
  • 86
  • 115
Budius
  • 39,391
  • 16
  • 102
  • 144
  • @Budius What do you mean by MEANINGFUL? does it mean a unique id related to each item? – Hamzeh Soboh May 21 '16 at 07:25
  • @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 data – Budius May 21 '16 at 07:29
  • 4
    It worked on `notifyItemRangeInserted` but not `setHasStableIds` although `getItemId` was returning `getTime()` for that item's date, which is unique. – Hamzeh Soboh May 21 '16 at 09:37