Carousel-Slider
Carousel is a component to show the users a slideshow, usually images using ViewPager2.
Implementation
- Add following lines, in viewPager’s parentView
android:clipChildren="false" android:clipToPadding="false"
- Add some horizontal margin/padding in viewPager for preview.
e.g. 40dp
- Add carousel effect using following line. By default, zoom effect is enabled. However, we can disable it by passing
false
as a parameterbinding.viewPager.addCarouselEffect(enableZoom = false)
- Add an
extension-function
inobject
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
video_zoom.mp4
Without Zoom Effect
video_simple.mp4