Reputation: 1222
I have a Fragment with a RecyclerView. It works as a chat.
I request to my backend the last 50 messages and I load them in the recycler view
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(layoutManager);
mAdapter = new ChatMessagesAdapter(recyclerView, messages, getActivity());
recyclerView.setAdapter(mAdapter);
recyclerView.getLayoutManager().scrollToPosition(messages.size()-1);
mAdapter.notifyDataSetChanged();
Then, when I scroll up I request more messages with OnScrollListener and I load them
messages.addAll(0, oldMessages);
mAdapter.notifyDataSetChanged();
mAdapter.setLoaded();
recyclerView.getLayoutManager().scrollToPosition((oldMessages.size()) -1);
But as I set the the recyclerView in the first load with
layoutManager.setStackFromEnd(true);
when I load the old messages the scroll moves first item shown(before the last) to the bottom.
How can I add old messages on top and continue the scrolling like if the items were there from the first load? Without move the focus to the bottom
Upvotes: 2
Views: 3235
Reputation: 21053
Use notifyItemRangeInserted instead of notifyDataSetChanged.
Use below code to update your adapter:
public void addList(List<ChatMessage> items) {
chatMessages.addAll(0, items);
notifyItemRangeInserted(0,items.size());
notifyItemChanged(items.size());//Only To update the last top item cause in my case it was the date header so i need to notify it
}
Upvotes: 8