在RecyclerView上,我可以通过以下方法突然滚动到所选项目的顶部:
((LinearLayoutManager) recyclerView.getLayoutManager()).scrollToPositionWithOffset(position, 0);
但是,这会突然将项目移到最高位置。我想移动到一个项目的顶部平滑的。
我也试过:
recyclerView.smoothScrollToPosition(position);
但是,它不能很好地工作,因为它没有将项目移动到选定的位置到顶部。它只是滚动列表,直到位置上的项目可见为止。
发布于 2019-12-11 11:38:24
CustomLinearLayout.kt :
class CustomLayoutManager(private val context: Context, layoutDirection: Int):
LinearLayoutManager(context, layoutDirection, false) {
companion object {
// This determines how smooth the scrolling will be
private
const val MILLISECONDS_PER_INCH = 300f
}
override fun smoothScrollToPosition(recyclerView: RecyclerView, state: RecyclerView.State, position: Int) {
val smoothScroller: LinearSmoothScroller = object: LinearSmoothScroller(context) {
fun dp2px(dpValue: Float): Int {
val scale = context.resources.displayMetrics.density
return (dpValue * scale + 0.5f).toInt()
}
// change this and the return super type to "calculateDyToMakeVisible" if the layout direction is set to VERTICAL
override fun calculateDxToMakeVisible(view: View ? , snapPreference : Int): Int {
return super.calculateDxToMakeVisible(view, SNAP_TO_END) - dp2px(50f)
}
//This controls the direction in which smoothScroll looks for your view
override fun computeScrollVectorForPosition(targetPosition: Int): PointF ? {
return this @CustomLayoutManager.computeScrollVectorForPosition(targetPosition)
}
//This returns the milliseconds it takes to scroll one pixel.
override fun calculateSpeedPerPixel(displayMetrics: DisplayMetrics): Float {
return MILLISECONDS_PER_INCH / displayMetrics.densityDpi
}
}
smoothScroller.targetPosition = position
startSmoothScroll(smoothScroller)
}
}
注意:上面的示例设置为水平方向,您可以在初始化期间传递垂直/水平。
如果将方向设置为"calculateDxToMakeVisible“垂直,则应将更改为"calculateDyToMakeVisible”(还要注意超级类型的调用返回值)
Activity/Fragment.kt:
...
smoothScrollerLayoutManager = CustomLayoutManager(context, LinearLayoutManager.HORIZONTAL)
recyclerView.layoutManager = smoothScrollerLayoutManager
.
.
.
fun onClick() {
// targetPosition passed from the adapter to activity/fragment
recyclerView.smoothScrollToPosition(targetPosition)
}
https://stackoverflow.com/questions/31235183
复制相似问题