Android Material Tabs in Kotlin
Last Updated :
25 Jul, 2024
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.
.gif)
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
1. 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>
2. 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.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
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.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
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.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
Similar Reads
Android Toast in Kotlin
A Toast is a short alert message shown on the Android screen for a short interval of time. Android Toast is a short popup notification which is used to display information when we perform any operation in our app. In this tutorial, we shall not just limit ourselves by creating a lame toast but also
3 min read
Kotlin Android Tutorial
Kotlin is a cross-platform programming language that may be used as an alternative to Java for Android App Development. Kotlin is an easy language so that you can create powerful applications immediately. Kotlin is much simpler for beginners to try as compared to Java, and this Kotlin Android Tutori
6 min read
Android TableLayout in Kotlin
TableLayout in Android is a ViewGroup subclass that is designed to align child views in rows and columns like a grid structure. It automatically arranges all the child elements into rows and columns without displaying any border lines between cells. The Table Layout's functionality is almost similar
4 min read
Android RelativeLayout in Kotlin
RelativeLayout in Android is a ViewGroup subclass, that allows users to position child views relative to each other (e.g., view A to the right of view B) or relative to the parent (e.g., aligned to the top of the parent). Instead of using LinearLayout, we have to use RelativeLayout to design the use
4 min read
Android ViewPager in Kotlin
ViewPager adds a sleek, swipeable interface that lets users effortlessly navigate between pages, just like flipping through a book. This feature is common in social media apps; for instance, WhatsApp greets you with three intuitive tabs: chats, status, and calls. This makes the app look cool. You've
5 min read
Android LinearLayout in Kotlin
LinearLayout in Android is a ViewGroup subclass, used to arrange child view elements one by one in a singular direction either horizontally or vertically based on the orientation attribute. We can specify the linear layout orientation using the android:orientation attribute. All the child elements a
2 min read
SearchView in Android with Kotlin
SearchView is a widget in android which provides a search interface with the help of which users can be able to make searches within the given list of data. In this search view, the user has to specify the search query. According to the search, query results will be populated within the listview. In
4 min read
Android WebView in Kotlin
WebView is a view that is used to display web pages inside the app. It is used to turn the app into a web application. In this article let's display the https://www.geeksforgeeks.org/ inside the Android Application using Kotlin. Note: To implement Android WebView in Java please refer How to use WebV
2 min read
Android ListView in Kotlin
ListView in Android is a ViewGroup which is used to display a scrollable list of items arranged in multiple rows. It is attached to an adapter which dynamically inserts the items into the list. The main purpose of the adapter is to retrieve data from an array or a database and efficiently push every
3 min read
Android RecyclerView in Kotlin
In this article, you will know how to implement RecyclerView in Android using Kotlin . Before moving further let us know about RecyclerView. A RecyclerView is an advanced version of ListView with improved performance. When you have a long list of items to show you can use RecyclerView. It has the ab
5 min read