(Smooth)ScrollToPosition doesn't work properly with RecyclerView

后端 未结 16 1300
既然无缘
既然无缘 2020-12-03 04:29

I\'m using basic RecyclerView with GridLayoutManager. I observed that nor smoothScrollToPosition nor scrollToPosition works properly.

a) when using smoothScrol

16条回答
  •  攒了一身酷
    2020-12-03 04:57

    So i was looking for a solution to get back to the top with a recyclerview inside another layout that has a view on top of it (in my case I had a LinearLayout with a TextView and my recyclerview inside). Because of that the smoothscroll would go only to half the way to the first item.

    Here's what I did which works really well (Kotlin solution):

    back_to_top.setOnClickListener {
            GlobalScope.launch(Dispatchers.Main) {
                GlobalScope.launch(Dispatchers.Main) {
                    recyclerview.layoutManager?.smoothScrollToPosition(recyclerview, RecyclerView.State(), 0)
                    delay((recyclerview.layoutManager as LinearLayoutManager).findLastVisibleItemPosition() * 100L)
                }.join()
                recyclerview.scrollToPosition(0)
            }
            back_to_top.visibility = View.GONE
        }
    }
    

    Here what I do is I smoothscroll to the first element and delay the scroll by 100ms times the last item visible and then call the scrollToPosition(0) (which goes to the top.correctly)

提交回复
热议问题