Android TabLayout With ViewPager and Fragment in Kotlin

In this article, we will learn how to use Android TabLayout with ViewPager and Fragment in Kotlin. Till now, we have seen some basic concepts of TabLayout. For example, Set custom theme, tab indicator colour etc. Now, we will use tabLayout and ViewPager together to make a scrollable view.

Let’s have a quick demo of things we want to cover in this tutorial –

Output

Tutorialwing Kotlin Android TabLayout With ViewPager And Fragment in Kotlin

Getting Started

TabLayout acts as container to show different tabs in application. It supports two mode – Fixed or Scrollable. In this post, we are going to use fixed mode. However, scrollable mode can be implemented in same manner.

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 TabLayoutWithViewPager. 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 Different Views 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 TabLayout With ViewPager in Kotlin

Follow steps below to use TabLayout with viewPager in newly created project –

  • Open res/values/strings.xml file. Then, add below code into it.
    <resources>
        <string name="app_name">TabLayoutWithViewPager</string>
        <string name="first_fragment">First Fragment</string>
        <string name="second_fragment">Second Fragment</string>
        <string name="third_fragment">Third Fragment</string>
    </resources>
    
  • Since we are going to implement android tabLayout with ViewPager and Fragment in Kotlin, we need to create different fragments that will be used with viewPager. So now, we are going to create three fragments. Follow steps below to do it –
    1. Create First Fragment

      Create new xml file, activity_main.xml, in res/layout folder. 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"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:background="@android:color/holo_blue_light">
      
          <TextView
              android:id="@+id/label"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              app:layout_constraintBottom_toBottomOf="parent"
              app:layout_constraintEnd_toEndOf="parent"
              app:layout_constraintStart_toStartOf="parent"
              app:layout_constraintTop_toTopOf="parent" />
      
      </androidx.constraintlayout.widget.ConstraintLayout>
      

      Here, we just want to show text message in ui. So, there is only TextView.

      Now, create new Kotlin file, FirstFragment.kt, in com.tutorialwing.tablayoutwithviewpager package. Then, add below code in it –

      package com.tutorialwing.tablayoutwithviewpager
      
      import android.os.Bundle
      import android.view.LayoutInflater
      import android.view.View
      import android.view.ViewGroup
      import androidx.fragment.app.Fragment
      import com.tutorialwing.tablayoutwithviewpager.databinding.FirstFragmentBinding
      
      class FirstFragment : Fragment() {
      
      	private lateinit var binding: FirstFragmentBinding
      
      	override fun onCreateView(
      		inflater: LayoutInflater,
      		container: ViewGroup?,
      		savedInstanceState: Bundle?
      	): View {
      		binding = FirstFragmentBinding.inflate(layoutInflater)
      		return binding.root
      	}
      
      	override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
      		super.onViewCreated(view, savedInstanceState)
      
      		setupData()
      	}
      
      	private fun setupData() {
      		binding.label.text = getString(R.string.first_fragment)
      	}
      }
      

      Here, we have written code to set text in textView after onViewCreated is method.

    2. Create Second Fragment

      Create new xml file, second_fragment.xml, in res/layout folder. 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"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:background="@android:color/holo_red_light">
      
          <TextView
              android:id="@+id/label"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              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, create new Kotlin file, SecondFragment.kt, in com.tutorialwing.tablayoutwithviewpager package . Then, add below code in it –

      package com.tutorialwing.tablayoutwithviewpager
      
      import android.os.Bundle
      import android.view.LayoutInflater
      import android.view.View
      import android.view.ViewGroup
      import androidx.fragment.app.Fragment
      import com.tutorialwing.tablayoutwithviewpager.databinding.SecondFragmentBinding
      
      class SecondFragment : Fragment() {
      
      	private lateinit var binding: SecondFragmentBinding
      
      	override fun onCreateView(
      		inflater: LayoutInflater,
      		container: ViewGroup?,
      		savedInstanceState: Bundle?
      	): View {
      		binding = SecondFragmentBinding.inflate(layoutInflater)
      		return binding.root
      	}
      
      	override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
      		super.onViewCreated(view, savedInstanceState)
      
      		setupData()
      	}
      
      	private fun setupData() {
      		binding.label.text = getString(R.string.second_fragment)
      	}
      }
      

      Here, we set text to textView having id label in onCreateMethod.

    3. Create Third Fragment

      Now, we are going to create to third fragment that we need to display in viewPager. So, create new xml file, third_fragment.xml, in res/layout folder. 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"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:background="@android:color/holo_orange_light">
      
          <TextView
              android:id="@+id/label"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              app:layout_constraintBottom_toBottomOf="parent"
              app:layout_constraintEnd_toEndOf="parent"
              app:layout_constraintStart_toStartOf="parent"
              app:layout_constraintTop_toTopOf="parent" />
      
      </androidx.constraintlayout.widget.ConstraintLayout>
      

      We have only use textView as we just to show text in fragment.

      Now, create new Kotlin file, ThirdFragment.kt, in com.tutorialwing.tablayoutwithviewpager package. Then, add below code in it –

      package com.tutorialwing.tablayoutwithviewpager
      
      import android.os.Bundle
      import android.view.LayoutInflater
      import android.view.View
      import android.view.ViewGroup
      import androidx.fragment.app.Fragment
      import com.tutorialwing.tablayoutwithviewpager.databinding.ThirdFragmentBinding
      
      class ThirdFragment : Fragment() {
      
      	private lateinit var binding: ThirdFragmentBinding
      
      	override fun onCreateView(
      		inflater: LayoutInflater,
      		container: ViewGroup?,
      		savedInstanceState: Bundle?
      	): View {
      		binding = ThirdFragmentBinding.inflate(layoutInflater)
      		return binding.root
      	}
      
      	override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
      		super.onViewCreated(view, savedInstanceState)
      
      		setupData()
      	}
      
      	private fun setupData() {
      		binding.label.text = getString(R.string.third_fragment)
      	}
      }
      

      Here, we set text of textView in fragment.

  • Now, we are going to use tabLayout and viewPager in xml file. So, 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">
    
        <com.google.android.material.tabs.TabLayout
            android:id="@+id/tabLayout"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    
        <androidx.viewpager.widget.ViewPager
            android:id="@+id/viewPager"
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/tabLayout" />
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    
  • Now, we need to create adapter for ViewPager. So, create new file, ViewPagerAdapter.kt, in com.tutorialwing.tablayoutwithviewpager package. Then, add below code in it –
    package com.tutorialwing.tablayoutwithviewpager
    
    import androidx.fragment.app.Fragment
    import androidx.fragment.app.FragmentManager
    import androidx.fragment.app.FragmentPagerAdapter
    
    class ViewPagerAdapter(fm: FragmentManager, var tabCount: Int) : FragmentPagerAdapter(fm) {
    
    	override fun getItem(position: Int): Fragment {
    		return when (position) {
    			0 -> FirstFragment()
    			1 -> SecondFragment()
    			2 -> ThirdFragment()
    			else -> FirstFragment()
    		}
    	}
    
    	override fun getCount(): Int {
    		return tabCount
    	}
    
    	override fun getPageTitle(position: Int): CharSequence {
    		return "Tab " + (position + 1)
    	}
    }
    
  • Now, we need to setup viewPager and tabLayout in Kotlin file. So, open MainActivity.kt file. Then, add below code in it –
    package com.tutorialwing.tablayoutwithviewpager
    
    import androidx.appcompat.app.AppCompatActivity
    import android.os.Bundle
    import com.google.android.material.tabs.TabLayout
    import com.tutorialwing.tablayoutwithviewpager.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)
    
    		setupTabLayout()
    		setupViewPager()
    	}
    
    	private fun setupViewPager() {
    		binding.viewPager.apply {
    			adapter = ViewPagerAdapter(supportFragmentManager, binding.tabLayout.tabCount)
    			addOnPageChangeListener(TabLayout.TabLayoutOnPageChangeListener(binding.tabLayout))
    		}
    	}
    
    	private fun setupTabLayout() {
    		binding.tabLayout.apply {
    			addTab(this.newTab().setText("Tab 1"))
    			addTab(this.newTab().setText("Tab 2"))
    			addTab(this.newTab().setText("Tab 3"))
    
    			// tabGravity = TabLayout.GRAVITY_FILL
    
    			addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
    				override fun onTabSelected(tab: TabLayout.Tab?) {
    					tab?.position?.let {
    						binding.viewPager.currentItem = it
    					}
    				}
    
    				override fun onTabUnselected(tab: TabLayout.Tab?) {
    				}
    
    				override fun onTabReselected(tab: TabLayout.Tab?) {
    				}
    			})
    		}
    	}
    }
    

    Here,

    1. setupViewPager(): Inside this method, we create adapter for viewPager and set it. After that we create page change listener for viewPager and set it to same as tab select listener of tabLayout.
    2. setupTabLayout(): In this method, we create 3 tabs for tabLayout. Then, we set tab select listener for tabLayout. We set view in viewPager as per tab selected in tabLayout.

Now, run the application. We will get output as below –
Tutorialwing Kotlin Android TabLayout With ViewPager And Fragment in Kotlin

That’s end of tutorial on Android TabLayout With ViewPager And Fragment in Kotlin.

Leave a Reply