Open In App

Android ViewPager in Kotlin

Last Updated : 30 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

  1. 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.
  2. 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.

new_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

Create Blank Fragment

name-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:

  1. ChatsFragment (xml file is generated automatically in res > layout folder)
  2. StatusFragment (xml file is generated automatically in res > layout folder)
  3. 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.



Next Article
Article Tags :
Practice Tags :

Similar Reads