【问题标题】:RecyclerView add items on top and continue scrollingRecyclerView 在顶部添加项目并继续滚动
【发布时间】:2017-10-16 10:45:04
【问题描述】:

我有一个带有 RecyclerView 的片段。它可以用作聊天。

我向后端请求最后 50 条消息,并将它们加载到回收站视图中

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();

然后,当我向上滚动时,我使用 OnScrollListener 请求更多消息并加载它们

messages.addAll(0, oldMessages);
mAdapter.notifyDataSetChanged();
mAdapter.setLoaded();
recyclerView.getLayoutManager().scrollToPosition((oldMessages.size()) -1);

但是当我在第一次加载时设置了 recyclerView

layoutManager.setStackFromEnd(true);

当我加载旧消息时,滚动将显示的第一项(在最后一项之前)移动到底部。

如何在顶部添加旧消息并继续滚动,就像项目从第一次加载时就在那里一样?无需将焦点移至底部

【问题讨论】:

    标签: android android-recyclerview


    【解决方案1】:

    使用 notifyItemRangeInserted 代替 notifyDataSetChanged

    使用以下代码更新您的适配器:

    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 
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-21
      • 2017-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-15
      • 1970-01-01
      • 2021-01-15
      相关资源
      最近更新 更多