1

sometimes I'm replacing all the data from my ArrayList datasource like so:

private ArrayList data;

public void replaceAll(ArrayList newItems) {
    this.data.clear();
    for (int i = 0; i < newItems.size(); i++) {
        this.data.set(i, newItems.get(i));
    }
    notifyDataSetChanged();
}

but if for example this.data.size() == 50; and newItems.size() == 30; and thus data changed from 50 children to 30, after I run notifyDataSetChanged() my RecyclerView scrolls to the next child.

(i.e if I was on position 15, it goes to 16)

This ONLY happens when the newData size is less than the old, and I can't figure why.


p.s1: I tried running:

int childCntWeLostAfterMutation = data.size() - newData.size();
notifyItemRangeChanged(0, newData.size());
notifyItemRangeRemoved(newData.size(), childCntWeLostAfterMutation);

but then things get worse. It scrolls a lot further behind, and it totally messes up the visible position.

p.s2: Please don't tell me to smoothScrollToPosition, it's super messy and I don't think it will work on my scenario.

p.s3: I am already using setHasStableIds(true) and my public long getItemId(int position) returns a unique ID for every child.

Please help!

SudoPlz
  • 20,996
  • 12
  • 82
  • 123

0 Answers0