[英]How to set item to center of Recycler view when selected
将您的自定义布局管理器定义为
class CenterLayoutManager : LinearLayoutManager {
constructor(context: Context) : super(context)
constructor(context: Context, orientation: Int, reverseLayout: Boolean) : super(context, orientation, reverseLayout)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes)
override fun smoothScrollToPosition(recyclerView: RecyclerView, state: RecyclerView.State, position: Int) {
val centerSmoothScroller = CenterSmoothScroller(recyclerView.context)
centerSmoothScroller.targetPosition = position
startSmoothScroll(centerSmoothScroller)
}
private class CenterSmoothScroller(context: Context) : LinearSmoothScroller(context) {
override fun calculateDtToFit(viewStart: Int, viewEnd: Int, boxStart: Int, boxEnd: Int, snapPreference: Int): Int = (boxStart + (boxEnd - boxStart) / 2) - (viewStart + (viewEnd - viewStart) / 2)
}
}
然后将此布局管理器分配给您的回收站视图
myRecyclerview.layoutManager =
CenterLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
在 recyclerview 的 item onClick 方法中使用
myRecyclerview.smoothScrollToPosition(position)
位置应该从 onBindViewHolder 获得
也使用 LinearSnapHelper 作为
val snapHelper = LinearSnapHelper()
snapHelper.attachToRecyclerView(myRecyclerview)
它将有效地控制滚动
还将滚动侦听器附加到 recyclerview 以在中心位置获取项目
Recyclerview.setOnScrollListener(object:
RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
var view=recyclerView[0]
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.