How to scale up Recycler View center item while scrolling in android?

后端 未结 4 1687
臣服心动
臣服心动 2020-12-16 05:41

I need to always highlight the center item in the recycler view while scrolling by scaling up.

4条回答
  •  情话喂你
    2020-12-16 06:03

    I slimmed down that solution and added the initial resize during onLayoutComplete. I didn't need vertical scrolling, so I took that part out.

    class CenterZoomLinearLayoutManager(
        context: Context,
        private val mShrinkDistance: Float = 0.9f,
        val mShrinkAmount: Float = 0.15f
    ) : LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false) {
    
        override fun onLayoutCompleted(state: RecyclerView.State?) {
            super.onLayoutCompleted(state)
            scaleChildren()
        }
    
        override fun scrollHorizontallyBy(dx: Int, recycler: RecyclerView.Recycler?, state: RecyclerView.State?): Int {
            return if (orientation == HORIZONTAL) {
                super.scrollHorizontallyBy(dx, recycler, state).also { scaleChildren() }
            } else {
                0
            }
        }
    
        private fun scaleChildren() {
            val midpoint = width / 2f
            val d1 = mShrinkDistance * midpoint
            for (i in 0 until childCount) {
                val child = getChildAt(i) as View
                val d = Math.min(d1, Math.abs(midpoint - (getDecoratedRight(child) + getDecoratedLeft(child)) / 2f))
                val scale = 1f - mShrinkAmount * d / d1
                child.scaleX = scale
                child.scaleY = scale
            }
        }
    }
    

    See https://github.com/pcholt/toy-card-carousel

提交回复
热议问题