Hey ! Welcome to my page .This article helps you to learn about the implementation of ViewPager2 with Fragments and TabLayout. Let’s get started.

TabLayout enhances you to display tabs horizontally. Well in this case, implementation of the ViewPager2 with TabLayout helps to create views in swipeable format. Incase if you wanna create swipeable views in Tabs, you can combine TabLayout, ViewPager2 and Fragments.

Preview

1. Make a project and add dependencies

Firstly ,Open the AndroidStudio and then create a new project.
Give project and package name and select language Kotlin and finish.
Now add the following dependencies to app/build.gradle.

implementation 'com.google.android.material:material:1.3.0'

Sync your project for gradle to import all required classes.

2. Adding TabLayout and ViewPager2 to Activity

activity_main.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">

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:backgroundTint="@color/black"
        app:layout_constraintTop_toTopOf="parent"
        app:tabContentStart="32dp"
        app:tabIndicatorAnimationMode="elastic"
        app:tabIndicatorColor="@color/white"
        app:tabIndicatorFullWidth="false"
        app:tabMode="scrollable"
        app:tabPaddingEnd="16dp"
        app:tabPaddingStart="16dp"
        app:tabRippleColor="@android:color/transparent"
        app:tabTextAppearance="?attr/textAppearanceSubtitle1"
        app:tabTextColor="#ffffff" />

    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toBottomOf="@id/tab_layout" />

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.kt :

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.tabs.TabLayout

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val viewPager: ViewPager2 = findViewById(R.id.view_pager)
        val tabLayout: TabLayout = findViewById(R.id.tab_layout)
    }
}

3. Create empty or blank fragments

In this app, I made a use of three fragments for previewing views between fragments.
Create three empty fragments with associated layouts so that we can add them to ViewPager2.
You shall go with below names.

  1. PetsFragments.kt
  2. CategoriesFragment.kt
  3. WishlistFragment.kt

Take reference of below empty fragments xml layouts and class with different backgrounds to parent.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    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"
    android:background="#C6122000"
    android:orientation="vertical"
    android:paddingTop="8dp"
    tools:context=".fragments.PetsFragment">

</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    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"
    android:background="#C6270000"
    android:orientation="vertical"
    android:paddingTop="8dp"
    tools:context=".fragments.CategoriesFragment">

</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    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"
    android:background="#AE89D5DF"
    android:orientation="vertical"
    android:paddingTop="8dp"
    tools:context=".fragments.WishlistFragment">

</LinearLayout>

PetsFragment.kt :

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup

class PetsFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_pets, container, false)
    }
}

Now we’re done with fragments but create 2 more empty fragments taking reference to above one. Let’s create a adapter for this to link up all those fragments.

4. Create FragmentStateAdapter

To provide Fragments to ViewPager2 we need an adapter class. Let’s create a class which extends to FragmentStateAdapter.

ParentFragmentPagerAdapter.kt :

import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter

class ParentFragmentPagerAdapter(
    fragmentActivity: FragmentActivity
) : FragmentStateAdapter(fragmentActivity) {

    override fun createFragment(position: Int): Fragment {
        return when (position) {
            0 -> PetsFragment()
            1 -> CategoriesFragment()
            else -> WishlistFragment()
        }
    }

    override fun getItemCount(): Int {
        return 3
    }
}

5. Link tabs with ViewPager and adapter

Finally, we create the TabLayoutMediator that links ViewPager2 and the TabLayout, it has 3 parameters which needs tabs and viewpager information to update fragment with correct tab.

public TabLayoutMediator(
      @NonNull TabLayout tabLayout,
      @NonNull ViewPager2 viewPager,
      @NonNull TabConfigurationStrategy tabConfigurationStrategy
) {
    this(tabLayout, viewPager, /* autoRefresh= */ true, tabConfigurationStrategy); 
}

Back in MainActivity.kt create an instance for adapter we have created and later pass that information to ViewPager2 below this way.

val pagerAdapter = ParentFragmentPagerAdapter(this)
viewPager.adapter = pagerAdapter

Now let’s make use of object TabLayoutMediator and connect Tabs, Fragments with Viewpager2 with TabConfigurationStrategy.

TabLayoutMediator(tabLayout, viewPager) { tab, position ->
    val tabNames = listOf("Pets", "Categories", "Wishlist")
    tab.text = tabNames[position]
}.attach()

And this is how your MainActivity should look like after making those changes.

MainActivity.kt :

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
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)
        setContentView(R.layout.activity_main)

        val viewPager: ViewPager2 = findViewById(R.id.view_pager)
        val tabLayout: TabLayout = findViewById(R.id.tab_layout)
        
        val pagerAdapter = ParentFragmentPagerAdapter(this)
        viewPager.adapter = pagerAdapter
        
        TabLayoutMediator(tabLayout, viewPager,) { tab, position ->
            val tabNames = listOf("Pets", "Categories", "Wishlist", "Needs")
            tab.text = tabNames[position]
        }.attach()
    }
}

That’s it, no more code changes required. Similarly test the current state of app by adding more fragments or changing existing one to learn more.

Now run the app and have a look at the preview and you will be able to swipe between different fragments. If not take reference from source code below I have shared. Go with the Design Changes if needed.

That’s it people I hope you found this information useful, thanks for reading.

6. External Resources

Iswarya Singh

Iswarya Singh is a student, pursuing her Bachelor of Technology in Computer science and Engineering. She is a technoid interested in Python, UI/UX Design Android Development and Java.


Connect with me


Here We Go Again : (

if (article == helpful) {
    println("Like and subscribe to blog newsletter.")
} else {
    println("Let me know what i should blog on.")
}

This site uses Akismet to reduce spam. Learn how your comment data is processed.