Android ViewPager2 Using Kotlin With Example

In this article, we will learn about android ViewPager2 using Kotlin. We will go through various example that demonstrates how to use different attributes of ViewPager2. For example,

In this article, we will get answer to questions like –

  • What is ViewPager2?
  • Why should we consider ViewPager2 while designing ui for any app?
  • What are possibilities using ViewPager2 while designing ui? etc.

Getting Started

We can define android ViewPager2 widget as below –

ViewPager2 is advanced version of androidx.viewpager.widget.ViewPager that supports right-to-left layout support, vertical orientation, modifiable Fragment collections etc.

Now, how do we use ViewPager2 in android application ?

Creating New Project

At first, we will create an application.
So, follow steps below to create any android project in Kotlin –

Step Description
1. Open Android Studio (Ignore if already done).
2. Go to File => New => New Project. This will open a new window. Then, under Phone and Tablet section, select Empty Activity. Then, click Next.
3. In next screen, select project name as ViewPager2. Then, fill other required details.
4. Then, clicking on Finish button creates new project.

Newbie in Android ?

Some very important concepts (Recommended to learn before you move ahead)

Before we move ahead, we need to setup for viewBinding to access Android ViewPager2 Using Kotlin file without using findViewById() method.

Setup ViewBinding

Add viewBinding true in app/build.gradle file.

 
 android { 
 	// OTHER CODE... 
 	buildFeatures { 
 		viewBinding true 
 	} 
 } 
 

Now, set content in activity using view binding.
Open MainActivity.kt file and write below code in it.

 
 class MainActivity : AppCompatActivity() { 
 	
 	private lateinit var binding: ActivityMainBinding 
 	
 	override fun onCreate(savedInstanceState: Bundle?) { 
 		super.onCreate(savedInstanceState) 
 		binding = ActivityMainBinding.inflate(layoutInflater) 
 		val view = binding.root 
 		setContentView(view) 
 	} 
 } 
 

Now, we can access view in Kotlin file without using findViewById() method.

Using ViewPager2 in Kotlin

Follow steps below to use ViewPager2 in newly created project –

  • We are using an image, tw_logo.png, in our application. So, download this image and save it in res/drawable folder.
    Tutorialwing Logo
  • Open res/values/strings.xml file. Then, add below code into it.
    <resources>
        <string name="app_name">ViewPager2</string>
    </resources>
    
  • Now, we need to create ui for single view inside viewPager2. So, create a new file, item_holder.xml, in res/layout folder. Then, add below code into it –

    <?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"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <ImageView
            android:id="@+id/labelHeader"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="20dp"
            android:contentDescription="@string/app_name"
            android:src="@drawable/tw_logo"
            app:layout_constraintBottom_toTopOf="@+id/label"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent" />
    
        <TextView
            android:id="@+id/label"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="20sp"
            android:textStyle="bold"
            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, we need to create an adapter for viewPager2. This adapter provides data to be displayed inside ViewPager2. So, create a new file, ViewPagerAdapter.kt, in com.tutorialwing.viewpager2 package.
    Then, add below code into it.

    package com.tutorialwing.viewpager2
    
    import android.content.Context
    import android.graphics.Color
    import android.view.LayoutInflater
    import android.view.ViewGroup
    import androidx.recyclerview.widget.RecyclerView
    import com.tutorialwing.viewpager2.databinding.ItemHolderBinding
    
    class ViewPagerAdapter(
    	private val context: Context,
    	private val labelList: MutableList<String>,
    	private val colorList: MutableList<String>
    ) : RecyclerView.Adapter<ViewPagerAdapter.ViewPagerHolder>() {
    
    	override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewPagerHolder {
    		val binding = ItemHolderBinding.inflate(LayoutInflater.from(parent.context), parent, false)
    		return ViewPagerHolder(binding)
    	}
    
    	override fun onBindViewHolder(holder: ViewPagerHolder, position: Int) {
    		val label = labelList[position]
    		val color = colorList[position]
    		holder.bind(label, color)
    	}
    
    	override fun getItemCount(): Int {
    		return labelList.size
    	}
    
    	class ViewPagerHolder(private var itemHolderBinding: ItemHolderBinding) :
    		RecyclerView.ViewHolder(itemHolderBinding.root) {
    		fun bind(label: String, color: String) {
    			itemHolderBinding.label.text = label
    			itemHolderBinding.root.setBackgroundColor(Color.parseColor(color))
    		}
    	}
    }
    

    Here, we have created an adapter class that extends recyclerView adapter. We have already covered about this adapter class in our tutorial on RecyclerView. Here, we set label and background based on number of position in adapter.

  • Open res/layout/activity_main.xml file. Then, add below code in it –
    <?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">
    
        <androidx.viewpager2.widget.ViewPager2
            android:id="@+id/viewPager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    

    Here, we have used ViewPager2 in xml file. Now, we are going to use it in Kotlin file and perform some operations.

  • We can also access it in Kotlin File, MainActivity.kt, as below –

    package com.tutorialwing.viewpager2
    
    import android.os.Bundle
    import androidx.appcompat.app.AppCompatActivity
    import androidx.viewpager2.widget.ViewPager2
    import com.tutorialwing.viewpager2.databinding.ActivityMainBinding
    
    class MainActivity : AppCompatActivity() {
    
    	private lateinit var binding: ActivityMainBinding
    
    	override fun onCreate(savedInstanceState: Bundle?) {
    		super.onCreate(savedInstanceState)
    
    		binding = ActivityMainBinding.inflate(layoutInflater)
    		setContentView(binding.root)
    
    		setupViewPager2()
    	}
    
    	private fun setupViewPager2() {
    		val list: MutableList<String> = ArrayList()
    		list.add("This is your First Screen")
    		list.add("This is your Second Screen")
    		list.add("This is your Third Screen")
    		list.add("This is your Fourth Screen")
    
    		val colorList: MutableList<String> = ArrayList()
    		colorList.add("#00ff00")
    		colorList.add("#ff0000")
    		colorList.add("#0000ff")
    		colorList.add("#f0f0f0")
    
    		// Set adapter to viewPager.
    		binding.viewPager.adapter = ViewPagerAdapter(this, list, colorList)
    	}
    }
    

    Here, we have prepared some data and set adapter to viewPager.

    At this point, run your android application. You will get output as shown below –
    Tutorialwing Android Kotlin ViewPager2 Using Kotlin With Example

  • Applying Animation While Navigating between Views

    What if you want to apply transformation while changing from one view to another ?

    We can do so using setPageTransformer() method.

    Now, follow steps below to apply transformation in viewPager2 using Kotlin –

    1. Create new file, ZoomOutPageTransformer.kt, in com.tutorialwing.viewpager2 package.. Then, add below code into it –
      package com.tutorialwing.viewpager2
      
      import android.view.View
      import androidx.viewpager2.widget.ViewPager2
      
      private const val MIN_SCALE = 0.85f
      private const val MIN_ALPHA = 0.5f
      
      class ZoomOutPageTransformer : ViewPager2.PageTransformer {
      
      	override fun transformPage(view: View, position: Float) {
      		view.apply {
      			val pageWidth = width
      			val pageHeight = height
      			when {
      				position < -1 -> { // [-Infinity,-1)
      					// This page is way off-screen to the left.
      					alpha = 0f
      				}
      				position <= 1 -> { // [-1,1]
      					// Modify the default slide transition to shrink the page as well
      					val scaleFactor = Math.max(MIN_SCALE, 1 - Math.abs(position))
      					val vertMargin = pageHeight * (1 - scaleFactor) / 2
      					val horzMargin = pageWidth * (1 - scaleFactor) / 2
      					translationX = if (position < 0) {
      						horzMargin - vertMargin / 2
      					} else {
      						horzMargin + vertMargin / 2
      					}
      
      					// Scale the page down (between MIN_SCALE and 1)
      					scaleX = scaleFactor
      					scaleY = scaleFactor
      
      					// Fade the page relative to its size.
      					alpha = (MIN_ALPHA +
      							(((scaleFactor - MIN_SCALE) / (1 - MIN_SCALE)) * (1 - MIN_ALPHA)))
      				}
      				else -> { // (1,+Infinity]
      					// This page is way off-screen to the right.
      					alpha = 0f
      				}
      			}
      		}
      	}
      }
      
    2. Then, add below code in MainActivity –
      binding.viewPager.setPageTransformer(ZoomOutPageTransformer())
      

      Using setPageTransformer() method, we have set that animation in viewPager2.

      As of now, MainActivity.kt file looks like below –

      package com.tutorialwing.viewpager2
      
      import android.os.Bundle
      import androidx.appcompat.app.AppCompatActivity
      import androidx.viewpager2.widget.ViewPager2
      import com.tutorialwing.viewpager2.databinding.ActivityMainBinding
      
      class MainActivity : AppCompatActivity() {
      
      	private lateinit var binding: ActivityMainBinding
      
      	override fun onCreate(savedInstanceState: Bundle?) {
      		super.onCreate(savedInstanceState)
      
      		binding = ActivityMainBinding.inflate(layoutInflater)
      		setContentView(binding.root)
      
      		setupViewPager2()
      	}
      
      	private fun setupViewPager2() {
      		val list: MutableList<String> = ArrayList()
      		list.add("This is your First Screen")
      		list.add("This is your Second Screen")
      		list.add("This is your Third Screen")
      		list.add("This is your Fourth Screen")
      
      		val colorList: MutableList<String> = ArrayList()
      		colorList.add("#00ff00")
      		colorList.add("#ff0000")
      		colorList.add("#0000ff")
      		colorList.add("#f0f0f0")
      
      		binding.viewPager.adapter = ViewPagerAdapter(this, list, colorList)
      		binding.viewPager.setPageTransformer(ZoomOutPageTransformer())
      	}
      }
      
    3. Now, run application. We will get output as shown below –
      Tutorialwing Android Kotlin ViewPager2 Using Kotlin Set PagerTransformation Animation in Transition
  • Enable back and forth navigation in ViewPager

    As of we now, we have not enable back button navigation in ViewPager2 using Kotlin, So, when you press back button app is closed directly. ViewPager2 provides us a way to move to previous view using viewPager.currentItem in onBackPress method.

    Open MainActivity.kt file. Then, add below code into it –

    	override fun onBackPressed() {
    		val viewPager = binding.viewPager
    		if (viewPager.currentItem == 0) {
    			// If the user is currently looking at the first step, allow the system to handle the
    			// Back button. This calls finish() on this activity and pops the back stack.
    			super.onBackPressed()
    		} else {
    			// Otherwise, select the previous step.
    			viewPager.currentItem = viewPager.currentItem - 1
    		}
    	}
    
  • Perform Action Using Page Change

    ViewPager2 provides a way to perform some action when we navigate from one view to another view. We can do so by registering callback using registerOnPageChangeCallback method.

    Add below code in MainActivity.kt file –

    		binding.viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
    
    			// Triggered when you select a new page
    			override fun onPageSelected(position: Int) {
    				super.onPageSelected(position)
    			}
    
    			/**
    			 * This method will be invoked when the current page is scrolled,
    			 * either as part of a programmatically initiated
    			 * smooth scroll or a user initiated touch scroll.
    			 */
    			override fun onPageScrolled(
    				position: Int,
    				positionOffset: Float,
    				positionOffsetPixels: Int
    			) {
    				super.onPageScrolled(position, positionOffset, positionOffsetPixels)
    			}
    
    			/**
    			 * Called when the scroll state changes.
    			 * Useful for discovering when the user begins dragging,
    			 * when a fake drag is started, when the pager is automatically settling
    			 * to the current page, or when it is fully stopped/idle.
    			 * state can be one of SCROLL_STATE_IDLE, SCROLL_STATE_DRAGGING or SCROLL_STATE_SETTLING.
    			 */
    			override fun onPageScrollStateChanged(state: Int) {
    				super.onPageScrollStateChanged(state)
    			}
    
    		})
    
  • Finally, code inside MainActivity.kt file would like below –
    package com.tutorialwing.viewpager2
    
    import android.os.Bundle
    import androidx.appcompat.app.AppCompatActivity
    import androidx.viewpager2.widget.ViewPager2
    import com.tutorialwing.viewpager2.databinding.ActivityMainBinding
    
    class MainActivity : AppCompatActivity() {
    
    	private lateinit var binding: ActivityMainBinding
    
    	override fun onCreate(savedInstanceState: Bundle?) {
    		super.onCreate(savedInstanceState)
    
    		binding = ActivityMainBinding.inflate(layoutInflater)
    		setContentView(binding.root)
    
    		setupViewPager2()
    	}
    
    	private fun setupViewPager2() {
    		val list: MutableList<String> = ArrayList()
    		list.add("This is your First Screen")
    		list.add("This is your Second Screen")
    		list.add("This is your Third Screen")
    		list.add("This is your Fourth Screen")
    
    		val colorList: MutableList<String> = ArrayList()
    		colorList.add("#00ff00")
    		colorList.add("#ff0000")
    		colorList.add("#0000ff")
    		colorList.add("#f0f0f0")
    
    		binding.viewPager.adapter = ViewPagerAdapter(this, list, colorList)
    		binding.viewPager.setPageTransformer(ZoomOutPageTransformer())
    
    		setupPageChangeCallback()
    	}
    
    	private fun setupPageChangeCallback() {
    		binding.viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
    
    			// Triggered when you select a new page
    			override fun onPageSelected(position: Int) {
    				super.onPageSelected(position)
    			}
    
    			/**
    			 * This method will be invoked when the current page is scrolled,
    			 * either as part of a programmatically initiated
    			 * smooth scroll or a user initiated touch scroll.
    			 */
    			override fun onPageScrolled(
    				position: Int,
    				positionOffset: Float,
    				positionOffsetPixels: Int
    			) {
    				super.onPageScrolled(position, positionOffset, positionOffsetPixels)
    			}
    
    			/**
    			 * Called when the scroll state changes.
    			 * Useful for discovering when the user begins dragging,
    			 * when a fake drag is started, when the pager is automatically settling
    			 * to the current page, or when it is fully stopped/idle.
    			 * state can be one of SCROLL_STATE_IDLE, SCROLL_STATE_DRAGGING or SCROLL_STATE_SETTLING.
    			 */
    			override fun onPageScrollStateChanged(state: Int) {
    				super.onPageScrollStateChanged(state)
    			}
    
    		})
    	}
    
    	override fun onBackPressed() {
    		val viewPager = binding.viewPager
    		if (viewPager.currentItem == 0) {
    			// If the user is currently looking at the first step, allow the system to handle the
    			// Back button. This calls finish() on this activity and pops the back stack.
    			super.onBackPressed()
    		} else {
    			// Otherwise, select the previous step.
    			viewPager.currentItem = viewPager.currentItem - 1
    		}
    	}
    }
    

Now, run the application. We will get output as below –
Tutorialwing Android Kotlin ViewPager2 Using Kotlin Set PagerTransformation Animation in Transition

Different Attributes of ViewPager2 in XML

Now, we will see how to use different attributes of Android ViewPager2 using Kotlin to customise it –

Set Id of ViewPager2

Many a time, we need id of View to access it in kotlin file or create ui relative to that view in xml file. So, we can set id of ViewPager2 using android:id attribute like below –

    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/viewPager2_ID"
        />

Here, we have set id of ViewPager2 as viewPager2_ID using android:id=”” attribute. So, if we need to reference this ViewPager2, we need to use this id – viewPager2_ID.

Set Width of ViewPager2

We use android:layout_width=”” attribute to set width of ViewPager2.
We can do it as below –

    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/viewPager2_ID"
        android:layout_width="wrap_content"
        />

Width can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value (like 20dp, 30dp etc.).

Set Height of ViewPager2

We use android:layout_height=”” attribute to set height of ViewPager2.
We can do it as below –

    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/viewPager2_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

Height can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value.

Set Padding of ViewPager2

We use android:padding=”” attribute to set padding of ViewPager2.
We can do it as below –

    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/viewPager2_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        />

Here, we have set padding of 10dp in ViewPager2 using android:padding=”” attribute.

Set Margin of ViewPager2

We use android:layout_margin=”” attribute to set margin of ViewPager2.
We can do it as below –

    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/viewPager2_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        />

Here, we have set margin of 10dp in ViewPager2 using android:layout_margin=”” attribute.

Set Background of ViewPager2

We use android:background=”” attribute to set background of ViewPager2.
We can do it as below –

    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/viewPager2_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#ff0000"
        />

Here, we have set background of color #ff0000 in ViewPager2 using android:background=”” attribute.

Set Visibility of ViewPager2

We use android:visibility=”” attribute to set visibility of ViewPager2.
We can do it as below –

    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/viewPager2_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="gone"
        />

Here, we have set visibility of ViewPager2 using android:visiblity=”” attribute. Visibility can be of three types – gone, visible and invisible

Till now, we have see how to use android ViewPager2 using Kotlin. We have also gone through different attributes of ViewPager2 to perform certain task. Let’s have a look at list of such attributes and it’s related task.

Different Attributes of Android ViewPager2 Widget

Below are the various attributes that are used to customise android ViewPager2 Widget. However, you can check the complete list of attributes of ViewPager2 in it’s official documentation site. Here, we are going to list some of the important attributes of this widget –

Some of the popular attributes of android viewPager2 inherited from viewGroup are –

Sr. XML Attributes Description
1 android:animateLayoutChanges Defines whether to run layout transition when there is any change in layout
2 android:animationCache Defines whether to create drawing cache for children by layout animation
3 android:clipToPadding Defines whether the ViewGroup will clip its children and resize (but not clip) any EdgeEffect to its padding, if padding is not zero
4 android:layoutAnimation Defines the layout animation to be used when the viewGroup is laid out for the first time
5 android:layoutMode Specifies the layout mode of the viewGroup

Some of the popular attributes of android viewPager2 inherited from View are –

Sr. XML Attributes Description
1 android:alpha Defines alpha to the view
2 android:background Defines drawable to the background
3 android:backgroundTint Defines tint to apply to the background
4 android:clickable Defines whether the view is clickable or not
5 android:elevation Defines elevation of the view
6 android:focusable Defines whether this view can take focus or not
7 android:id Defines id of the view
8 android:visibility Defines the visibility(VISIBLE, INVISIBLE, GONE) of the view

We have seen different attributes of ViewPager2 and how to use it. If you wish to visit post to learn more about it

Thus, we have seen what is ViewPager2, how can we use android ViewPager2 using Kotlin ? etc. We also went through different attributes of android ViewPager2.

Leave a Reply