我正在尝试做什么。
使用 RecyclerView 创建一个简单的轮播。
问题
例如,请参阅下面附带的 gif 。
问题
以下是自定义 LayoutManager
的代码open class CarouselLayoutManager(
context: Context,
orientation: Int,
reverseLayout: Boolean
) : LinearLayoutManager(context, orientation, reverseLayout) {
private val mShrinkAmount = 0.15f
private val mShrinkDistance = 0.9f
override fun onLayoutChildren(recycler: RecyclerView.Recycler?, state: RecyclerView.State?) {
scrollVerticallyBy(0, recycler, state)
super.onLayoutChildren(recycler, state)
}
override fun scrollHorizontallyBy(dx: Int, recycler: RecyclerView.Recycler?, state: RecyclerView.State?): Int {
val orientation = orientation
if (orientation == LinearLayoutManager.HORIZONTAL) {
val scrolled = super.scrollHorizontallyBy(dx, recycler, state)
val midpoint = width / 2f
val d0 = 0f
val d1 = mShrinkDistance * midpoint
val s0 = 1f
val s1 = 1f - mShrinkAmount
for (i in 0 until childCount) {
val child = getChildAt(i)
val childMidpoint = (getDecoratedRight(child) + getDecoratedLeft(child)) / 2f
val d = Math.min(d1, Math.abs(midpoint - childMidpoint))
val scale = s0 + (s1 - s0) * (d - d0) / (d1 - d0)
child.scaleX = scale
child.scaleY = scale
}
return scrolled
} else {
return 0
}
}
override fun scrollVerticallyBy(dy: Int, recycler: RecyclerView.Recycler?, state: RecyclerView.State?): Int {
val orientation = orientation
if (orientation == LinearLayoutManager.VERTICAL) {
val scrolled = super.scrollVerticallyBy(dy, recycler, state)
val midpoint = height / 2f
val d0 = 0f
val d1 = mShrinkDistance * midpoint
val s0 = 1f
val s1 = 1f - mShrinkAmount
for (i in 0 until childCount) {
val child = getChildAt(i)
val childMidpoint = (getDecoratedBottom(child) + getDecoratedTop(child)) / 2f
val d = Math.min(d1, Math.abs(midpoint - childMidpoint))
val scale = s0 + (s1 - s0) * (d - d0) / (d1 - d0)
child.scaleX = scale
child.scaleY = scale
}
return scrolled
} else {
return 0
}
}
}
答案 0 :(得分:0)
最后,我通过使用这个库/示例
解决了这个问题以下是最终结果。
有关完整代码,请参阅Carousel Demo
答案 1 :(得分:0)
以scrollVerticallyBy(0, recycler, state)
方法调用onLayoutCompleted()