Skip to main content

How to add tab layout with ViewPager2 in Kotlin Android

How to add tab layout with ViewPager2 in Kotlin Android.

Here's a step-by-step tutorial on how to add TabLayout with ViewPager2 in Kotlin Android:

Step 1: Create a new Android project in Kotlin.

Step 2: Open the layout file for the activity where you want to add the TabLayout and ViewPager2 (e.g., activity_main.xml).

Step 3: Add the TabLayout and ViewPager2 to your layout file. For example, you can use the following code:



Step 4: In your activity's Kotlin file (e.g., MainActivity.kt), initialize the TabLayout and ViewPager2:

val tabLayout = findViewById<TabLayout>(
val viewPager = findViewById<ViewPager2>(

Step 5: Create a data class to hold the information for each tab. For example:

data class Tab(val title: String, val fragment: Fragment)

Step 6: Create a list of tabs that you want to display in the TabLayout. For example:

val tabs = listOf(
Tab("Tab 1", Fragment1()),
Tab("Tab 2", Fragment2()),
Tab("Tab 3", Fragment3())

Step 7: Create a FragmentStateAdapter to manage the fragments for each tab. This adapter will provide the appropriate fragment for each tab. For example:

class TabAdapter(fragmentActivity: FragmentActivity, private val tabs: List<Tab>) :
FragmentStateAdapter(fragmentActivity) {

override fun getItemCount(): Int = tabs.size

override fun createFragment(position: Int): Fragment = tabs[position].fragment

Step 8: Set up the ViewPager2 with the TabLayout and the TabAdapter. For example:

viewPager.adapter = TabAdapter(this, tabs)
TabLayoutMediator(tabLayout, viewPager) { tab, position ->
tab.text = tabs[position].title

Step 9: Run your app and you should see the TabLayout with the ViewPager2 displaying the fragments for each tab.

That's it! You have successfully added TabLayout with ViewPager2 in your Kotlin Android app.