Reputation: 11
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()
}
Upvotes: 1
Views: 593
Reputation: 81
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)
Upvotes: 0