Android ViewPager2 Scroll Animation: Adjust Height and Opacity/Alpha using PageTransformer (Kotlin)

June 18, 2019
/*
val paddingX = 16.dpToPx(resources.displayMetrics)
val paddingY = 16.dpToPx(resources.displayMetrics)
viewPager.setPadding(paddingX, paddingY, paddingX, paddingY)
 */

val transformer = ViewPager2.PageTransformer { page, position ->
    page.apply {
        val r = 1 - Math.abs(position)
        page.alpha = 0.25f + r
        page.scaleY = 0.75f + r * 0.25f
    }
}

viewPager.setPageTransformer(transformer)

You might want to implement Card layout for the pages for a more obvious animation effects.

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_margin="8dp"
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        app:cardUseCompatPadding="true"
        app:cardCornerRadius="16dp">

    <LinearLayout android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:layout_gravity="center"
                  android:orientation="vertical">

        <!-- Content -->


    </LinearLayout>
</androidx.cardview.widget.CardView>

NOTE: Refer Setup ViewPager2 for Android (Kotlin).

NOTE: Refer dpToPx.

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.