Android Material Tabs in Kotlin - GeeksforGeeks

30 Aug, 2021
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. 
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 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     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">      <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.Bundleimport androidx.fragment.app.Fragmentimport android.view.LayoutInflaterimport 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.Bundleimport androidx.fragment.app.Fragmentimport android.view.LayoutInflaterimport 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     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="Code Chef" />    </LinearLayout>
Code for 3rd fragment i.e. LeetFragment.kt
Kotlin
import android.os.Bundleimport androidx.fragment.app.Fragmentimport android.view.LayoutInflaterimport 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     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="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.Fragmentimport androidx.fragment.app.FragmentManagerimport 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.AppCompatActivityimport android.os.Bundleimport androidx.appcompat.widget.Toolbarimport androidx.viewpager.widget.ViewPagerimport 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
Picked
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Broadcast Receiver in Android With Example
Services in Android with Example
How to Create and Add Data to SQLite Database in Android?
Content Providers in Android with Example
Android RecyclerView in Kotlin
Broadcast Receiver in Android With Example
Services in Android with Example
Content Providers in Android with Example
Android RecyclerView in Kotlin
Android UI Layouts