[英]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.