(Smooth)ScrollToPosition doesn't work properly with RecyclerView

后端 未结 16 1037
既然无缘
既然无缘 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 05:02

    This extension is so useful, try please.

    fun RecyclerView.smoothSnapToPosition(position: Int, snapMode: Int = LinearSmoothScroller.SNAP_TO_START) {
            val smoothScroller = object : LinearSmoothScroller(this.context) {
                override fun getVerticalSnapPreference(): Int = snapMode
                override fun getHorizontalSnapPreference(): Int = snapMode
            }
            smoothScroller.targetPosition = position
            layoutManager?.startSmoothScroll(smoothScroller)
        }
    
    0 讨论(0)
  • 2020-12-03 05:03

    recyclerView.getLayoutManager().smoothScrollToPosition(recyclerView,new RecyclerView.State(),currentPosition);

    0 讨论(0)
  • 2020-12-03 05:03

    Another reason why any of the before mentioned solutions may not work is if your RecyclerView is embedded in a NestedScrollView. In this case you have to call the scroll action on the NestedScrollView.

    for example:

    nestedScrollview.smoothScrollTo(0,0)
    
    0 讨论(0)
  • 2020-12-03 05:05

    If you are trying to do a quick scroll to a position at the top of the RecyclerView, just use LinearLayoutManager.scrollToPositionWithOffset with 0 as the offset.

    Example:

    mLinearLayoutManager = new LinearLayoutManager(this);
    recyclerView.setLayoutManager(mLinearLayoutManager);
    
    mLinearLayoutManager.scrollToPositionWithOffset(myPosition, 0);
    

    smoothScrollToPosition is very slow. If you want something fast go with scrollToPositionWithOffset.

    0 讨论(0)
提交回复
热议问题