简体   繁体   English

notifyDataSetChanged 上的反向布局 RecyclerView 中不需要的滚动

[英]unwanted scroll in reverse layout RecyclerView on notifyDataSetChanged

here is the image explaining the problem so that you can understand better这是解释问题的图像,以便您更好地理解

Hi friends, I was building a chat module, I have used recycler-view for that with reverse layout (Linear layout manager).嗨朋友们,我正在构建一个聊天模块,我使用了 recycler-view 和反向布局(线性布局管理器)。 I am facing a problem is that whenever I am loading the next page of chat, it is back scrolling to a few positions back.我面临的一个问题是,每当我加载下一页聊天时,它都会向后滚动到几个位置。 I don't why it happening.我不知道为什么会这样。 I am using Kotlin, when I removed just the reverse layout then it is working very fine.我正在使用 Kotlin,当我只删除反向布局时,它工作得很好。 Here is my code...这是我的代码...

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

when I am using layoutManager.stackFromEnd = true then I am not facing the problem but it is taking me back to zero position当我使用 layoutManager.stackFromEnd = true 时,我没有遇到问题,但它让我回到零 position

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

adding the elements to ArrayList将元素添加到 ArrayList

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

This is quite old question, but In case if anybody is stuck with same issue then this might help.这是一个很老的问题,但如果有人遇到同样的问题,那么这可能会有所帮助。 This worked for me.这对我有用。 So you have to save RecyclerView state before notifyDataSetChanged() and then restore state after notify.所以你必须在 notifyDataSetChanged() 之前保存 RecyclerView state ,然后在通知之后恢复 state 。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM