RecyclerView滑动到指定Item并置顶
1 2 3 4 5 6 7 8 9 10 11 12
| import android.content.Context import androidx.recyclerview.widget.LinearSmoothScroller
class TopLinearSmoothScroller(context: Context?) : LinearSmoothScroller(context) { public override fun getVerticalSnapPreference(): Int { return SNAP_TO_START }
override fun getHorizontalSnapPreference(): Int { return SNAP_TO_START } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| import android.content.Context import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView
class TopScrollLinearLayoutManager(context: Context?, orientation: Int, reverseLayout: Boolean) : LinearLayoutManager(context, orientation, reverseLayout) {
override fun smoothScrollToPosition( recyclerView: RecyclerView?, state: RecyclerView.State?, position: Int ) { val linearSmoothScroller = TopLinearSmoothScroller(recyclerView?.context) linearSmoothScroller.targetPosition = position startSmoothScroll(linearSmoothScroller) } }
|
0x03 RecyclerView中使用
设置recyclerView的layoutManager为自定义的TopScrollLinearLayoutManager,然后直接调用 smoothScrollToPosition()
方法就可以滚动到指定的位置并且置顶了。
1 2 3 4 5 6 7
| recyclerView.layoutManager = TopScrollLinearLayoutManager( this, LinearLayoutManager.HORIZONTAL, false )
recyclerView.smoothScrollToPosition(1)
|