Android ViewPager in Kotlin
Last Updated :
30 Jul, 2024
ViewPager adds a sleek, swipeable interface that lets users effortlessly navigate between pages, just like flipping through a book. This feature is common in social media apps; for instance, WhatsApp greets you with three intuitive tabs: chats, status, and calls. This makes the app look cool. You’ve probably noticed it guiding you through an app’s features when you first install it.
However, with ViewPager1 being deprecated by Android, we’ll be working with ViewPager2 along with TabLayout to create a simple Swipeable interface.
By the end of this article, you’ll be equipped to implement this powerful feature in any app, making your user experience as seamless and engaging as the pros. Let’s get started!
Why ViewPager2?
ViewPager2 was introduced to replace ViewPager1 due to several improvements and enhancements that address some limitations of the original ViewPager.
Some Advantages of ViewPager2 are:
- Vertical orientation support:
Although it was possible to create vertical orientation in ViewPager1 using Custom code and workarounds, still it wasn’t a built-in feature and required additional effort. Whereas ViewPager2 supports vertical paging in addition to traditional horizontal paging. You can enable vertical paging for a ViewPager2 element by setting its android:orientation attribute. - Right-To-Left support:
ViewPager1 had limited right-to-left (RTL) support, often requiring workarounds. ViewPager2 offers enhanced RTL support out of the box, ensuring proper navigation and layout consistency.
Brief Go Through
We will start by adding the TabLayout and ViewPager2 in the activity_main.xml. After doing this, we will add three blank fragments to the app. We will change the text as per our needs in all the three XML files of the fragments. Now, we will create MyFragmentStateAdapter.kt class which extends the FragmentStateAdapter. In this we have to work with 2 main functions getItemCount() and createFragment(). Finally, we just need to call the ViewPager2 and TabLayout and then set the MyFragmentStateAdapter instance to ViewPager2’s adapter. Then we use the TabLayoutMediator to link the TabLayout and the ViewPager2.
A sample video is given below to get practical knowledge about the idea that we will be implementing.
Important Functions used in the FragmentStateAdapter
- getItemCount() – Returns the number of fragments to show.
- createFragment() – Provide a new Fragment associated with the specified position
Step by Step Implementation
Step 1: Create a project with the Empty Activity
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Make sure you have chosen Kotlin as the language while creating the project.

Create New Project
Step 2: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. Here we have just added the TabLayout and ViewPager2.
XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.google.android.material.tabs.TabLayout
android:id="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
app:tabGravity="fill"
app:tabMode="fixed" />
<androidx.viewpager2.widget.ViewPager2
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/tab_layout"
android:labelFor="@id/tab_layout" />
</RelativeLayout>
Step 3: Adding the blank fragments
This is the path to create a blank fragment in Android Studio.
The Path is: File > New > Fragment > Fragment (Blank)

Create Blank Fragment

Enter Name and Click Finish
After clicking on the Blank Fragment, name the fragment and click on finish. Make three fragments in total.
We have made the following 3 fragments:
- ChatsFragment (xml file is generated automatically in res > layout folder)
- StatusFragment (xml file is generated automatically in res > layout folder)
- CallFragment (xml file is generated automatically in res > layout folder)
Step 4: Working with the XML files of fragments
In each fragment, we have changed the text and added the basic things to our XML file like textColor, textSize, etc.
*Customize Fragment according to your need*
ChatsFragment:
XML
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ChatsFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="GFG Chats"
android:textSize="32sp"
android:textColor="#4CAF50"
android:textStyle="bold" />
</FrameLayout>
StatusFragment:
XML
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".StatusFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="GFG Status"
android:textSize="32sp"
android:textColor="#4CAF50"
android:textStyle="bold" />
</FrameLayout>
CallFragment:
XML
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".CallFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="GFG Calls"
android:textSize="32sp"
android:textColor="#4CAF50"
android:textStyle="bold" />
</FrameLayout>
Step 5: Adding the FragmentStateAdapter
We extend our ‘MyFragmentStateAdapter’ with ‘FragmentStateAdapter’ and this FragmentStateAdapter requires a ‘ FragmentActivity ‘ as parameter
Kotlin
package com.aashushaikh.viewpagerarticle
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
class MyFragmentStateAdapter(fragmentActivity: FragmentActivity): FragmentStateAdapter(fragmentActivity) {
override fun getItemCount(): Int {
return 3
}
override fun createFragment(position: Int): Fragment {
return when (position) {
0 -> ChatsFragment()
1 -> StatusFragment()
2 -> CallFragment()
else -> ChatsFragment()
}
}
}
Step 6: Working with MainActivity.kt
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file.
Kotlin
package com.aashushaikh.viewpagerarticle
import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_main)
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}
val tabLayout = findViewById<TabLayout>(R.id.tab_layout)
val viewPager2 = findViewById<ViewPager2>(R.id.view_pager_2)
val myAdapter = MyFragmentStateAdapter(this)
viewPager2.adapter = myAdapter
TabLayoutMediator(tabLayout, viewPager2) { tab: TabLayout.Tab, position: Int ->
when (position) {
0 -> {
tab.text = "Chats"
tab.setIcon(R.drawable.ic_chat)
}
1 -> {
tab.text = "Status"
tab.setIcon(R.drawable.ic_status)
}
2 -> {
tab.text = "Calls"
tab.setIcon(R.drawable.ic_call)
}
}
}.attach()
}
}
TabLayoutMediator mediator to link a TabLayout with a ViewPager2. The mediator will synchronize the ViewPager2’s position with the selected tab when a tab is selected, and the TabLayout’s scroll position when the user drags the ViewPager2.
Output:
A vertical swipe can also be achieved by just using the android:orientation property in xml ViewPager2. (Try it)
You can also try to do use this concept to make a similar thing in java. Click here to get the article.
Similar Reads
Android WebView in Kotlin
WebView is a view that is used to display web pages inside the app. It is used to turn the app into a web application. In this article let's display the https://www.geeksforgeeks.org/ inside the Android Application using Kotlin. Note: To implement Android WebView in Java please refer How to use WebV
2 min read
Android ListView in Kotlin
ListView in Android is a ViewGroup which is used to display a scrollable list of items arranged in multiple rows. It is attached to an adapter which dynamically inserts the items into the list. The main purpose of the adapter is to retrieve data from an array or a database and efficiently push every
3 min read
ViewFlipper in Android with Kotlin
View Flipper is a UI component in Android which is used to flip the view within the screen in the android application. The View Flipper class is an extension of ViewAnimator class. With the help of this, we can simply flip the views. In this article, we will take a look at How we can use ViewFlipper
4 min read
Android View Shaker in Kotlin
View Shaker is an android animation in which the UI of the screen vibrates for a specific interval of time. We can implement this View shaker to the specific views of the application. View Shaker provides different animation effects which we can add to our views such as bounce, fade, float, and othe
4 min read
Android LinearLayout in Kotlin
LinearLayout in Android is a ViewGroup subclass, used to arrange child view elements one by one in a singular direction either horizontally or vertically based on the orientation attribute. We can specify the linear layout orientation using the android:orientation attribute. All the child elements a
2 min read
Android RecyclerView in Kotlin
In this article, you will know how to implement RecyclerView in Android using Kotlin . Before moving further let us know about RecyclerView. A RecyclerView is an advanced version of ListView with improved performance. When you have a long list of items to show you can use RecyclerView. It has the ab
5 min read
Android Image Slider using ViewPager in Kotlin
Image slider is seen in most e-commerce applications that display advertisements on the home screen. This slider displays the advertisement banners which users can slide to view the others. In this article, we will take a look at Implementing the image slider using ViewPager in Android using Kotlin.
5 min read
Image Slider in Android using ViewPager
When talking about Android Apps, the first thing that comes to mind is variety. There are so many varieties of Android apps providing the user with beautiful dynamic UI. One such feature is to navigate in the Android Apps using the left and right swipes as opposed to clicking on Buttons. Not only do
4 min read
SearchView in Android with Kotlin
SearchView is a widget in android which provides a search interface with the help of which users can be able to make searches within the given list of data. In this search view, the user has to specify the search query. According to the search, query results will be populated within the listview. In
4 min read
Android Material Tabs in Kotlin
In Android, TabLayout is a new element introduced in the Design Support library. It provides a horizontal layout to display tabs on the screen. We can display more screens on a single screen using tabs. We can quickly swipe between the tabs. TabLayout is basically ViewClass required to be added into
5 min read