Carousel (slider) effect using ViewPager2

Carousel (slider) effect using ViewPager2


Carousel is a component to show the users a slideshow, usually images using ViewPager2.


  1. Add following lines, in viewPager’s parentViewandroid:clipChildren="false" android:clipToPadding="false"
  2. Add some horizontal margin/padding in viewPager for preview. e.g. 40dp
  3. Add carousel effect using following line. By default, zoom effect is enabled. However, we can disable it by passing false as a parameter binding.viewPager.addCarouselEffect(enableZoom = false)
  4. Add an extension-function in object type class:fun ViewPager2.addCarouselEffect(enableZoom: Boolean = true) { clipChildren = false // No clipping the left and right items clipToPadding = false // Show the viewpager in full width without clipping the padding offscreenPageLimit = 3 // Render the left and right items (getChildAt(0) as RecyclerView).overScrollMode = RecyclerView.OVER_SCROLL_NEVER // Remove the scroll effect val compositePageTransformer = CompositePageTransformer() compositePageTransformer.addTransformer(MarginPageTransformer((20 * Resources.getSystem().displayMetrics.density).toInt())) if (enableZoom) { compositePageTransformer.addTransformer { page, position -> val r = 1 - abs(position) page.scaleY = (0.80f + r * 0.20f) } } setPageTransformer(compositePageTransformer) }

Zoom Effect


Without Zoom Effect



View Github

Leave a Reply

Your email address will not be published. Required fields are marked *