【问题标题】:unwanted scroll in reverse layout RecyclerView on notifyDataSetChangednotifyDataSetChanged 上的反向布局 RecyclerView 中不需要的滚动
【发布时间】:2020-10-04 13:33:06
【问题描述】:

here is the image explaining the problem so that you can understand better

朋友们好, 我正在构建一个聊天模块,我使用了 recycler-view 和反向布局(线性布局管理器)。我面临的一个问题是,每当我加载下一页聊天时,它都会向后滚动到几个位置。我不知道为什么会这样。我正在使用 Kotlin,当我只删除反向布局时,它工作得很好。这是我的代码...

    val layoutManager = LinearLayoutManager(requireContext(), RecyclerView.VERTICAL, true)
    chatRecyclerView?.setHasFixedSize(true)
    layoutManager.stackFromEnd = false
    chatRecyclerView?.layoutManager = layoutManager

当我使用 layoutManager.stackFromEnd = true 时,我没有遇到问题,但它让我回到零位置

      chatRecyclerView?.setOnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY ->
            log("Scrolling_view $scrollY $oldScrollY $scrollX $oldScrollX")

            activity?.runOnUiThread {

                val layoutManager =
                    chatRecyclerView?.layoutManager as LinearLayoutManager
                val firstVisiblePosition = layoutManager.findLastVisibleItemPosition()


                    if (firstVisiblePosition == arrayList.size - 1) {
                        if (!viewModel.loadingNewList) {
                            viewModel.conversationId.skip =
                                viewModel.arrayList.size.toDouble()
                            viewModel.getChatMessages()
                        }
                }
            }
        }

将元素添加到 ArrayList

    arrayList.add(
                 listItems()
                 )
        chatRecyclerView?.post {
            chatMessagesAdapter.notifyDataSetChanged()
        }

【问题讨论】:

  • 作为一种解决方法,您可以尝试添加mRecyclerView.scrollToPosition(**The item position before loading**);
  • 它正在滚动到该位置,但将该位置引导至底部。因为滚动到位置将是反向布局中的最后一个可见位置

标签: android android-recyclerview reverse linearlayoutmanager


【解决方案1】:

这是一个很老的问题,但如果有人遇到同样的问题,那么这可能会有所帮助。这对我有用。所以你必须在 notifyDataSetChanged() 之前保存 RecyclerView 的状态,然后在 notify 之后恢复状态。

val recyclerViewState = chatRecyclerView.layoutManager?.onSaveInstanceState() 
chatMessagesAdapter.notifyDataSetChanged()
chatRecyclerView.layoutManager?.onRestoreInstanceState(recyclerViewState)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-16
    • 2017-04-12
    • 1970-01-01
    • 2018-11-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多