Carousel Animation In Recycler view

PRIYANKA AGARWAL
2 min readOct 17, 2021

--

Carousel animation is generally implemented with view pager as is in view pager, we show 1 item at a time. So, it becomes easy for anyone to implement carousel animation with view pager. But it becomes difficult for someone who has already implemented recycler view in the project and now has to implement this. I also faced the same problem. By searching everywhere on internet I finally got a solution to this.

To make recyclerview behave like viewpager

snapHelper = PagerSnapHelper()
snapHelper?.attachToRecyclerView(recyclerView)

Make focused item of recyclerview larger and display preview of previous and next items.

override fun scrollHorizontallyBy(dx: Int, recycler: Recycler, state: RecyclerView.State): Int {
val orientation = orientation
return if (orientation == 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.scaleY = scale
child.pivotY = child.height.toFloat()
}
scrolled
} else {
0
}
}

You will achieve the result as shown in the image. Carousel animation will happen keeping bottom of the items aligned.

If want items to be centered as shown in below image then remove the child.pivotY property from layoutmanager.

Full project on github.

--

--