1

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()
        }
  • As a workaround, you could try adding `mRecyclerView.scrollToPosition(**The item position before loading**);` – Biscuit Jun 15 '20 at 08:21
  • it is scrolling to that position but leading the position to bottom. as scroll to positions will be the last visible position in reverse layout – Codebrew Developer Jun 15 '20 at 10:22

1 Answers1

0

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)
Satpal Yadav
  • 81
  • 1
  • 12