Home > Net >  Android ViewPager2, previous and next item darken processing
Android ViewPager2, previous and next item darken processing

Time:02-24

enter image description here

As shown in the picture above, I want to darken the previous & next items in ViewPager2.

setPageTransformer(object : ViewPager2.PageTransformer {
            override fun transformPage(page: View, position: Float) {
                page.translationX = -pageTranslationX * position
                page.scaleY = 1 - (0.15f * abs(position))
            }
        })

I'm showing the preview with the code above, but I couldn't find a way to darken it.

Is there a good solution?

CodePudding user response:

You can utilize the position parameter, that maps to the current position of the page, to get a color shade based on the page position; this also will benefit in grading the colors between the most darken & most lighten colors so that the color changes gradually:

  • Create two color resource for the lighten color and darken colors
  • Use ColorUtils.blendARGB() to get a color based on percentage of the position.
  • Set the new background color to the root view of the page
setPageTransformer(object : ViewPager2.PageTransformer {
        override fun transformPage(page: View, position: Float) {
            page.translationX = -pageTranslationX * position
            page.scaleY = 1 - (0.15f * abs(position))
            
            val startColor = ContextCompat.getColor(this, R.color.light_blue)
            val endColor = ContextCompat.getColor(this, R.color.dark_blue)
            val color = ColorUtils.blendARGB(startColor, endColor, abs(position))
            val view = page.findViewById<LinearLayout>(R.id.page_root) //  this is the page fragment root view (make sure to set its id)
            view?.setBackgroundColor(color)
            
        }
    })

Result:

  • Related