[英]unwanted scroll in reverse layout RecyclerView on notifyDataSetChanged
嗨朋友們,我正在構建一個聊天模塊,我使用了 recycler-view 和反向布局(線性布局管理器)。 我面臨的一個問題是,每當我加載下一頁聊天時,它都會向后滾動到幾個位置。 我不知道為什么會這樣。 我正在使用 Kotlin,當我只刪除反向布局時,它工作得很好。 這是我的代碼...
val layoutManager = LinearLayoutManager(requireContext(), RecyclerView.VERTICAL, true)
chatRecyclerView?.setHasFixedSize(true)
layoutManager.stackFromEnd = false
chatRecyclerView?.layoutManager = layoutManager
當我使用 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()
}
}
}
}
將元素添加到 ArrayList
arrayList.add(
listItems()
)
chatRecyclerView?.post {
chatMessagesAdapter.notifyDataSetChanged()
}
這是一個很老的問題,但如果有人遇到同樣的問題,那么這可能會有所幫助。 這對我有用。 所以你必須在 notifyDataSetChanged() 之前保存 RecyclerView state ,然后在通知之后恢復 state 。
val recyclerViewState = chatRecyclerView.layoutManager?.onSaveInstanceState()
chatMessagesAdapter.notifyDataSetChanged()
chatRecyclerView.layoutManager?.onRestoreInstanceState(recyclerViewState)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.