RecyclerView scroll to position when a new item is added

后端 未结 7 1699
南笙
南笙 2020-12-31 03:18

I want my RecyclerView to scroll to the bottom when a new item is added to the list. Below is my code:

RecyclerView.LayoutManager layoutManager = new LinearL         


        
7条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-31 04:03

    adapter.registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() {
        override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
            super.onItemRangeInserted(positionStart, itemCount)
    
            val msgCount = adapter.getItemCount()
            val lastVisiblePosition = 
                linearLayoutManager.findLastCompletelyVisibleItemPosition()
    
            if (lastVisiblePosition == -1 || positionStart >= msgCount - 1 && 
                lastVisiblePosition == positionStart - 1) {
                recyclerView.scrollToPosition(positionStart)
            } else {
                recyclerView.scrollToPosition(adapter.getItemCount() - 1);
            }
        }
    })
    

提交回复
热议问题