Open In App

Android Material Tabs in Kotlin

Last Updated : 30 Aug, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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 our layout(XML) for creating Sliding Tabs. 

What we are going to build in this article? 

In this article, we are going to develop an application that will have three tabs and users can slide from one tab to another just like in WhatsApp. For this, we will be using TabLayout. A sample GIF is given below to get an idea about what we are going to do in this article. 

Step by Step Implementation

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.

Step 2: Add dependency

Add a dependency to get access to all the material components and click on sync.

   implementation ‘com.google.android.material:material:1.4.0’

Step 3: Set theme and toolbar

Navigate to res > values > color.xml, set some vibrant colors. Add the following script code for colors.

XML




<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#0F9D58</color>
    <color name="colorPrimaryDark">#056008</color>
    <color name="colorAccent">#E39D36</color>
  <resources>


Now, remove the default toolbar from the screen, and we will make a custom toolbar. Navigate to res > values > styles.xml (for latest version of android studio, res > values > themes > theme.xml) and change parentTheme .

XML




<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
       <!-- Customize your theme here. -->
       <item name="colorPrimary">@color/colorPrimary</item>
       <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
       <item name="colorAccent">@color/colorAccent</item>
</style>


Step 4: Working with activity_main layout

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.

XML




<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
    android:layout_width="match_parent"
    android:layout_height="match_parent">
  
    <com.google.android.material.appbar.AppBarLayout
        android:id="@+id/appBarLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:layout_constraintBottom_toTopOf="@+id/viewPager"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">
  
        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
  
        <com.google.android.material.tabs.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabBackground="@color/colorPrimary"
            app:tabGravity="fill"
            app:tabMode="fixed"
            app:tabTextColor="@android:color/white" />
    </com.google.android.material.appbar.AppBarLayout>
  
    <androidx.viewpager.widget.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/appBarLayout">
          
    </androidx.viewpager.widget.ViewPager>
  
</androidx.constraintlayout.widget.ConstraintLayout>


Step 5: Set three tabs

We need to create three fragment classes and their three respective layouts. Here is the code for 1st fragment i.e. GeeksFragment.kt 

Kotlin




import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.ViewGroup
  
class GeeksFragment : Fragment() {
    // inflate the layout
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ) =
        inflater.inflate(R.layout.fragment_geeks, container, false)!!
}


The corresponding layout, fragment_geeks.xml 

XML




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">
  
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="GeeksForGeeks" />
    
</LinearLayout>


Code for the 2nd fragment i.e. CodeFragment.kt 

Kotlin




import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.ViewGroup
  
class CodeFragment : Fragment() {
    // inflate the layout
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ) =
        inflater.inflate(R.layout.fragment_code, container, false)!!
}


The corresponding layout, fragment_code.xml

XML




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">
  
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Code Chef" />
    
</LinearLayout>


Code for 3rd fragment i.e. LeetFragment.kt

Kotlin




import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.ViewGroup
  
class LeetFragment : Fragment() {
    // inflate the layout
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ) =
        inflater.inflate(R.layout.fragment_leet, container, false)!!
}


The corresponding layout, fragment_leet.xml

XML




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">
  
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Leet Code" />
    
</LinearLayout>


Step 6: Create a ViewPagerAdapter class

To connect all our fragments with the ViewPager, we need an adapter class. we will pass the list of instances of fragment class and their title to show on the tabs. Below is the code for ViewPagerAdapter.kt Comments are added inside the code to understand the code in more detail. 

Kotlin




import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentStatePagerAdapter
  
class ViewPagerAdapter(supportFragmentManager: FragmentManager) :
    FragmentStatePagerAdapter(supportFragmentManager) {
  
    // declare arrayList to contain fragments and its title
    private val mFragmentList = ArrayList<Fragment>()
    private val mFragmentTitleList = ArrayList<String>()
  
    override fun getItem(position: Int): Fragment {
        // return a particular fragment page
        return mFragmentList[position]
    }
  
    override fun getCount(): Int {
        // return the number of tabs
        return mFragmentList.size
    }
  
    override fun getPageTitle(position: Int): CharSequence{
        // return title of the tab
        return mFragmentTitleList[position]
    }
  
    fun addFragment(fragment: Fragment, title: String) {
        // add each fragment and its title to the array list
        mFragmentList.add(fragment)
        mFragmentTitleList.add(title)
    }
}


Step 7: Working with the MainActivity.kt file

Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.

Kotlin




import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.appcompat.widget.Toolbar
import androidx.viewpager.widget.ViewPager
import com.google.android.material.tabs.TabLayout
  
class MainActivity : AppCompatActivity() {
  
    private lateinit var pager: ViewPager // creating object of ViewPager
    private lateinit var tab: TabLayout  // creating object of TabLayout
    private lateinit var bar: Toolbar    // creating object of ToolBar
  
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
  
        // set the references of the declared objects above
        pager = findViewById(R.id.viewPager)
        tab = findViewById(R.id.tabs)
        bar = findViewById(R.id.toolbar)
  
        // To make our toolbar show the application 
          // we need to give it to the ActionBar
        setSupportActionBar(bar)
  
        // Initializing the ViewPagerAdapter
        val adapter = ViewPagerAdapter(supportFragmentManager)
  
        // add fragment to the list
        adapter.addFragment(GeeksFragment(), "GeeksForGeeks")
        adapter.addFragment(CodeFragment(), "Code Chef")
        adapter.addFragment(LeetFragment(), "Leet Code")
  
        // Adding the Adapter to the ViewPager
        pager.adapter = adapter
        
        // bind the viewPager with the TabLayout.
        tab.setupWithViewPager(pager)
    }
}


Now, run the app

Output:

Source Code: Click Here



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads