我有一个配置了各种扩展功能的 RecyclerView 以居中并查看下一项:
fun RecyclerView.pageSnap() = this.post {
if (this.onFlingListener == null) PagerSnapHelper().attachToRecyclerView(this)
}
fun RecyclerView.snapCenterWithMargin(left: Int, top: Int, right: Int, bottom: Int) {
val offsetItemDecoration = SnapCenterWithMargin(left, top, right, bottom)
this.addItemDecoration(offsetItemDecoration)
}
private class SnapCenterWithMargin(
private val left: Int,
private val top: Int,
private val right: Int,
private val bottom: Int
) : RecyclerView.ItemDecoration() {
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
view.measure(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
val position = parent.getChildAdapterPosition(view)
val firstItem = 0
val lastItem = state.itemCount - 1
when (position) {
firstItem -> {
val firstPadding = (parent.width) / 2 - view.measuredWidth / 2
outRect.set(firstPadding, 0, 0, 0)
}
lastItem -> {
val lastPadding = (parent.width) / 2 - view.measuredWidth / 2
outRect.set(0, 0, lastPadding, 0)
}
else -> {
outRect.set(left, top, right, bottom)
}
}
}
}
问题是这种方法的 ListAdapter 动画不好。然后我尝试移动到 ViewPager2 但我无法获得这种行为(请参阅下一个屏幕并保持项目居中)。