简体   繁体   中英

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). 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. 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

      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.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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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