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

Jun 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.

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.