Cube in Scaling Animation with ViewPager in Android

30 Aug, 2021
The Android ViewPager has become a very interesting concept among Android apps. It enables users to switch smoothly between fragments which have a common UI and it’s the best way to make your app extraordinary from others. ViewPagers provide visual continuity. They basically keep track of which page is visible and then ask PageAdapter to display the next page in the hierarchy. Not just this, it even allows you to create all sorts of awesome slide effects and animations! 
In this article, we are going to implement cube-in-scaling animation using ViewPager. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language. 
There are 3 basic components for the full implementation of ViewPager:
An Activity that contains ViewPager and chief UI.
A set of Fragments that are viewed as separate pages in ViewPager.
FragmentPageAdapter or FragmentStatePageAdapter returns the correct fragment which needs to be displayed next.
For example, refer to the article – ViewPager Using Fragments in Android with Example.
Here, we will make an image slider using ViewPager and then will apply cube-in-scaling-animation.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.
Step 2: Designing the UI
Below is the code for the activity_main.xml file. We have added only a ViewPager to show the images. Below is the complete code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout     xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainActivity">      <!-- viewpager to show images -->    <androidx.viewpager.widget.ViewPager        android:id="@+id/viewPagerMain"        android:layout_width="match_parent"        android:layout_height="match_parent"        app:layout_constraintBottom_toBottomOf="parent"        app:layout_constraintEnd_toEndOf="parent"        app:layout_constraintStart_toStartOf="parent"        app:layout_constraintTop_toTopOf="parent" />  </androidx.constraintlayout.widget.ConstraintLayout>
Now, Create a new Layout Resource File item.xml inside the app > res > layout folder. Below is the code of the item.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout     xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent">      <!-- image viewer to view the images -->    <ImageView        android:id="@+id/imageViewMain"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:layout_margin="10dp"        android:contentDescription="image" />  </LinearLayout>
Step 3: Working with the ViewPagerAdapter.kt and MainActivity.kt files
First, create a ViewPagerAdapter class, an Adapter for the ViewPager. Below is the complete code of ViewPagerAdapter.kt class. Comments are added inside the code to understand each line of the code.
Kotlin
import android.content.Contextimport android.view.LayoutInflaterimport android.view.Viewimport android.view.ViewGroupimport android.widget.ImageViewimport android.widget.LinearLayoutimport androidx.viewpager.widget.PagerAdapterimport java.util.*  internal class ViewPagerAdapter(private val context: Context, private val images: IntArray) : PagerAdapter() {      // Layout Inflater    var mLayoutInflater: LayoutInflater    override fun getCount(): Int {        // return the number of images        return images.size    }      init {        mLayoutInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater    }      override fun isViewFromObject(view: View, `object`: Any): Boolean {        return view === `object` as LinearLayout    }      override fun instantiateItem(container: ViewGroup, position: Int): Any {                  // inflating the item.xml        val itemView: View = mLayoutInflater.inflate(R.layout.item, container, false)          // referencing the image view from the item.xml file        val imageView: ImageView = itemView.findViewById(R.id.imageViewMain)          // setting the image in the imageView        imageView.setImageResource(images[position])          // Adding the View        Objects.requireNonNull(container).addView(itemView)        return itemView    }      override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {        container.removeView(`object` as LinearLayout)    }}
 Below is the complete code for the MainActivity.kt file. Comments are added inside the code to understand each line of the code.
Kotlin
import android.os.Bundleimport androidx.appcompat.app.AppCompatActivityimport androidx.viewpager.widget.ViewPager  class MainActivity : AppCompatActivity() {          // creating object of ViewPager    lateinit var mViewPager: ViewPager      // images array    private var images = intArrayOf(R.drawable.a1, R.drawable.a2, R.drawable.a3, R.drawable.a4)      // Creating Object of ViewPagerAdapter    private lateinit var mViewPagerAdapter: ViewPagerAdapter      override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)        setContentView(R.layout.activity_main)          // Initializing the ViewPager Object        mViewPager = findViewById(R.id.viewPagerMain)          mViewPager.setPageTransformer(true, CubeInScalingAnimation())          // Initializing the ViewPagerAdapter        mViewPagerAdapter = ViewPagerAdapter(this@MainActivity, images)          // Adding the Adapter to the ViewPager        mViewPager.adapter = mViewPagerAdapter    }}
Step 4: Create a new class CubeInScalingAnimation.kt to apply the Cube-in-scaling-animation. Below is the complete code for the CubeInScalingAnimation.kt file. Comments are added inside the code to understand each line of the code.
Kotlin
import android.view.Viewimport androidx.viewpager.widget.ViewPagerimport kotlin.math.abs  class CubeInScalingAnimation : ViewPager.PageTransformer {      override fun transformPage(page: View, position: Float) {        page.cameraDistance = 20000F        when {            position < -1 -> {   //{-infinity,-1}                // page offset to left side                page.alpha = 0F            }            position <= 0 -> {                // transition from left                 // side of page to current page                page.alpha = 1F                page.pivotX = page.width.toFloat()                page.rotationY = 90F * abs(position)            }            position <= 1 -> {                // transition form current                 // page to right side                page.alpha = 1F                page.pivotX = 0F                page.rotationY = -90F * abs(position)            }            //{1,+infinity}            else -> { //Page offset to right side                page.alpha = 0F            }        }          when {            // transition between page1 and page2            abs(position) <= 0.5 -> {                page.scaleY = Math.max(0.4f, 1 - abs(position))            }            abs(position) <= 1 -> {                page.scaleY = Math.max(0.4f, abs(position))            }        }    }}
Now, run the app
Output:
Source Code: Click Here
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android SDK and it's Components
How to Communicate Between Fragments in Android?
Flutter - Custom Bottom Navigation Bar
Retrofit with Kotlin Coroutine in Android
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android UI Layouts
How to Communicate Between Fragments in Android?
Kotlin Array
Retrofit with Kotlin Coroutine in Android