Android TabLayout Using Kotlin With Example

In this article, we will learn about android TabLayout using Kotlin. We will go through various example that demonstrates how to use different attributes of TabLayout. For example,

In this article, we will get answer to questions like –

  • What is TabLayout?
  • Why should we consider TabLayout while designing ui for any app?
  • What are possibilities using TabLayout while designing ui? etc.

Getting Started

We can define android TabLayout widget as below –

TabLayout acts as container to display tabs. We can have either have fixed tabs or scrollable tabs in it.

Now, how do we use TabLayout in android application ?

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 TabLayout. 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 TabLayout 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 in Kotlin

Follow steps below to use TabLayout in newly created project –

  • Open res/values/strings.xml file. Then, add below code into it.
    <resources>
        <string name="app_name">TabLayout</string>
        <string name="selected_tab">Selected tab: %1$s</string>
    </resources>
    
  • 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_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent">
    
            <com.google.android.material.tabs.TabItem
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Tab 1" />
    
            <com.google.android.material.tabs.TabItem
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Tab 2" />
    
        </com.google.android.material.tabs.TabLayout>
    
        <TextView
            android:id="@+id/textView"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:gravity="center"
            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>
    

    Here,

    • We have used TabLayout in xml file. Inside TabLayout, we have defined two TabItems. There is a TextView inside this xml file. We are going to update text of this textView based on selected tabs in TabLayout.
  • Till now, we have just defined TabLayout in xml file. Now, we will access it in Kotlin file. Then, update text of textView based on selected tab. Open MainActivity.kt file. Then, add below code in it –

    package com.tutorialwing.tablayout
    
    import androidx.appcompat.app.AppCompatActivity
    import android.os.Bundle
    import com.google.android.material.tabs.TabLayout
    import com.tutorialwing.tablayout.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()
    	}
    
    	private fun setupTabLayout() {
    
    		val selectedPosition = binding.tabLayout.selectedTabPosition
    		binding.textView.text =
    			getString(R.string.selected_tab, binding.tabLayout.getTabAt(selectedPosition)?.text)
    
    		binding.tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
    
    			override fun onTabSelected(tab: TabLayout.Tab?) {
    				binding.textView.text = getString(R.string.selected_tab, tab?.text)
    			}
    
    			override fun onTabReselected(tab: TabLayout.Tab?) {
    				// Write code to handle tab reselect
    			}
    
    			override fun onTabUnselected(tab: TabLayout.Tab?) {
    				// Write code to handle tab reselect
    			}
    		})
    	}
    }
    

    Here,

    1. Inside setupTabLayout() method, we set text of textView as text of currently selected tab.
    2. We have also added a tab select listener that will be called whenever any tab is selected, unselected or reselected.

Now, run the application. We will get output as below –
Tutorialwing Kotlin Android TabLayout Using Kotlin With Example

Set Icon in TabItem inside TabLayout

Using attribute android:icon=”” we can set menu in tabItem. Follow steps below to do it –

  • Let’s add some drawable icons. We need two icons – ic_favourite and ic_music. Follow steps to add Raster image or vector image in android project.
  • Now, open activity_main.xml file and add android:icon=”” attribute for each tabItem. Finally, code inside xml file is –

    <?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_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent">
    
            <com.google.android.material.tabs.TabItem
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:icon="@drawable/ic_favorite"
                android:text="Tab 1" />
    
            <com.google.android.material.tabs.TabItem
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:icon="@drawable/ic_music"
                android:text="Tab 2" />
    
        </com.google.android.material.tabs.TabLayout>
    
        <TextView
            android:id="@+id/textView"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:gravity="center"
            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>
    
  • run application, we will get output as below –
    Tutorialwing Kotlin Android TabLayout Using Kotlin With Example Set Icon in TabItem

Fixed or Scrollable Modes of TabLayout

There are two modes of tab layout. They are –

  • Fixed: In this mode, tabs will be aligned inside screen. If it goes out of the screen, it won’t be visible. We should use it when there is less number of tabs.
  • Scrollable: In this mode, tabs can be aligned outside screen. We just need to scroll right or left to see hidden tabs. We should use it when there is no fixed number of tabs or higher number of tabs in application.

Create Badge for TabItem in TabLayout

We often come across a situation when we need to show counts of item present inside selected tab. We can do so using attribute tab.orCreateBadge as below –

val badge = tab?.orCreateBadge
badge?.number = tab?.position!!

Follow steps below to do it –

  • Open MainActivity.kt file. Then, add below code in it –
    package com.tutorialwing.tablayout
    
    import androidx.appcompat.app.AppCompatActivity
    import android.os.Bundle
    import com.google.android.material.tabs.TabLayout
    import com.tutorialwing.tablayout.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()
    	}
    
    	private fun setupTabLayout() {
    
    		val selectedPosition = binding.tabLayout.selectedTabPosition
    		binding.textView.text =
    			getString(R.string.selected_tab, binding.tabLayout.getTabAt(selectedPosition)?.text)
    
    		binding.tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
    
    			override fun onTabSelected(tab: TabLayout.Tab?) {
    				binding.textView.text = getString(R.string.selected_tab, tab?.text)
    
    				val badge = tab?.orCreateBadge
    				badge?.number = tab?.position!!
    			}
    
    			override fun onTabReselected(tab: TabLayout.Tab?) {
    				// Write code to handle tab reselect
    			}
    
    			override fun onTabUnselected(tab: TabLayout.Tab?) {
    				// Write code to handle tab reselect
    			}
    		})
    	}
    }
    
  • Run application, we will get output as shown below –
    Tutorialwing Kotlin Android TabLayout Using Kotlin With Example Set Badge in TabItem

Set Custom Style of TabLayout Using themes.xml

Follow steps below to set custom style of tabLayout –

  1. Open themes.xml file. Then, add below code in it –
        <style name="AppTabLayout" parent="Widget.Design.TabLayout">
            <item name="tabMaxWidth">@dimen/tab_max_width</item>
            <item name="tabIndicatorColor">?attr/colorAccent</item>
            <item name="tabIndicatorHeight">4dp</item>
            <item name="tabPaddingStart">6dp</item>
            <item name="tabPaddingEnd">6dp</item>
            <item name="tabBackground">?attr/colorPrimary</item>
            <item name="tabTextAppearance">@style/AppTabTextAppearance</item>
            <item name="tabSelectedTextColor">@android:color/holo_orange_light</item>
            <item name="tabTextColor">@android:color/background_light</item>
        </style>
    
        <style name="AppTabTextAppearance" parent="TextAppearance.Design.Tab">
            <item name="android:textSize">12sp</item>
            <item name="android:textColor">@android:color/holo_orange_light</item>
            <item name="textAllCaps">false</item>
        </style>
    
  2. Now, open activity_main.xml file. set theme in tabLayout as below –

        <com.google.android.material.tabs.TabLayout
            // OTHER CODE
            style="@style/AppTabLayout"
            app:tabTextAppearance="@style/AppTabTextAppearance">
    

    Finally, code inside xml file is –

    <?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_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:tabMode="fixed"
            style="@style/AppTabLayout"
            app:tabTextAppearance="@style/AppTabTextAppearance">
    
            <com.google.android.material.tabs.TabItem
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:icon="@drawable/ic_favorite"
                android:text="Tab 1" />
    
            <com.google.android.material.tabs.TabItem
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:icon="@drawable/ic_music"
                android:text="Tab 2" />
    
        </com.google.android.material.tabs.TabLayout>
    
        <TextView
            android:id="@+id/textView"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:gravity="center"
            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>
    

Run application, we will get output as below –
Tutorialwing Kotlin Android TabLayout Set Custom Theme example

Different Attributes of TabLayout in XML

Now, we will see how to use different attributes of Android TabLayout using Kotlin to customise it –

Set Id of TabLayout

Many a time, we need id of View to access it in kotlin file or create ui relative to that view in xml file. So, we can set id of TabLayout using android:id attribute like below –

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tabLayout_ID"
        />

Here, we have set id of TabLayout as tabLayout_ID using android:id=”” attribute. So, if we need to reference this TabLayout, we need to use this id – tabLayout_ID.

Set Width of TabLayout

We use android:layout_width=”” attribute to set width of TabLayout.
We can do it as below –

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tabLayout_ID"
        android:layout_width="wrap_content"
        />

Width can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value (like 20dp, 30dp etc.).

Set Height of TabLayout

We use android:layout_height=”” attribute to set height of TabLayout.
We can do it as below –

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tabLayout_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

Height can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value.

Set Padding of TabLayout

We use android:padding=”” attribute to set padding of TabLayout.
We can do it as below –

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tabLayout_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        />

Here, we have set padding of 10dp in TabLayout using android:padding=”” attribute.

Set Margin of TabLayout

We use android:layout_margin=”” attribute to set margin of TabLayout.
We can do it as below –

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tabLayout_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        />

Here, we have set margin of 10dp in TabLayout using android:layout_margin=”” attribute.

Set Background of TabLayout

We use android:background=”” attribute to set background of TabLayout.
We can do it as below –

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tabLayout_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#ff0000"
        />

Here, we have set background of color #ff0000 in TabLayout using android:background=”” attribute.

Set Visibility of TabLayout

We use android:visibility=”” attribute to set visibility of TabLayout.
We can do it as below –

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tabLayout_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="gone"
        />

Here, we have set visibility of TabLayout using android:visibility=”” attribute. Visibility can be of three types – gone, visible and invisible

Till now, we have see how to use android TabLayout using Kotlin. We have also gone through different attributes of TabLayout to perform certain task. Let’s have a look at list of such attributes and it’s related task.

We have seen different attributes of TabLayout and how to use it. If you wish to visit post to learn more about it

Thus, we have seen what is TabLayout, how can we use android TabLayout using Kotlin ? etc. We also went through different attributes of android TabLayout.

Leave a Reply