How to Implement Tabs, ViewPager and Fragment in Android using Kotlin?
Last Updated :
08 Aug, 2024
In some Android apps, Tabs are used, which allows developers to combine multiple tasks (operations) on a single activity. On the other hand, it provides a different look to that app. It is also possible to provide a different feel like left and right swipes by using ViewPager. And to implement this topic, a few terms are required such as ViewPager, Fragments, and TabLayout. For practice purposes, Kotlin programming language is used in this article.
What are TabLayout, ViewPager, and Fragment?
- TabLayout: This view allows us to make use of multiple tabs in the Android app. This Layout holds different tabs. In this article, tabs are used to navigate from one Fragment to another Fragment.
- ViewPager: This view allows us to make use of the left and right swipe features to show another fragment.
- Fragments: This is a part of the Activity. This view is necessary, to do multiple tasks in a single activity. The Fragment also makes use of a layout file which contains view/s as needed.
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: Create Fragments
- Go to app > res > layout > right-click > New > Layout Resource File and after that, it asks for the file name then gives “layout_login” as the name of that layout file.
- Use the same method to create another layout file “layout_signup”.
- After that, use the following code for the “layout_login.xml” file. Here one TextView is shown.
XML
<?xml version="1.0" encoding="utf-8"?>
<!-- This linear layout is used to show elements
in vertical or in horizontal linear manner -->
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<!-- This TextView indicates new fragment is open -->
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Login Fragment"
android:textColor="#0F9D58"
android:textSize="25sp"
android:textStyle="bold" />
</LinearLayout>
- Below is the code for the layout_signup.xml file.
XML
<?xml version="1.0" encoding="utf-8"?>
<!-- This linear layout is used to show elements
in vertical or in horizontal linear manner -->
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<!-- This TextView indicates new fragment is open -->
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Signup Fragment"
android:textColor="#0F9D58"
android:textSize="25sp"
android:textStyle="bold" />
</LinearLayout>
- To create Fragment class, right-click on the first package of java directory which is located at app > java > “com.example.gfgtabdemo”, where "gfgtabdemo" is the project name in a small case. Move cursor on “New” and select “Kotlin file/class”.

- Give “LoginFragment” as a name to that file and select the “class” option as shown in the below screenshot.
selecting the “class” option- To create a Fragment, it is necessary to make this class as a child of the Fragment class by using the “:” symbol. And override the “onCreateView” method to set the layout resource file to that fragment file as shown in the following code snippet.
- Use the above procedure to create the “SignupFragment” file.
- After that, use the following code in the “LoginFragment.kt” file.
Kotlin
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
// Here ":" symbol is indicate that LoginFragment
// is child class of Fragment Class
class LoginFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View? {
return inflater.inflate(
R.layout.layout_login, container, false
)
}
// Here "layout_login" is a name of layout file
// created for LoginFragment
}
- Use the following code in the “SignupFragment.kt” file.
Kotlin
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
// Here ":" symbol is indicate that SignupFragment
// is child class of Fragment Class
class SignupFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View? {
return inflater.inflate(
R.layout.layout_signup, container, false
)
}
// Here "layout_signup" is a name of layout file
// created for SignFragment
}
Step 3: Theme Configuration
- Open “styles.xml” which is placed inside of folder “app > res > values > styles.xml” as shown in the image below.

- Add the following code inside of <resources> tag in styles.xml.
XML
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<style name="AppTheme.AppBarOverlay"
parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="AppTheme.PopupOverlay"
parent="ThemeOverlay.AppCompat.Light" />
- Below is the complete code for the complete styles.xml file.
XML
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<style name="AppTheme.AppBarOverlay"
parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="AppTheme.PopupOverlay"
parent="ThemeOverlay.AppCompat.Light" />
</resources>
- After that open, the “AndroidManifest.xml” file placed inside of folders ”app > manifest > AndroidManifest.xml”. We need to set the theme “@style/AppTheme.NoActionBar” inside of <activity> tag. To do the same type the highlighted line in the following screenshot, inside of that activity tag, in which you want to use tab layout.
setting the theme “@style/AppTheme.NoActionBar” inside of tagStep 4: Adding Required Views
For the implementation of this topic, it is important to add some views. To do the same first, open build.gradle (Module: app) file, located at “Gradle Script > build.gradle (Module: app)”, and add the following dependency inside of dependencies block. And don’t forget to click on “sync now”. This dependency is required, to make use of “appbar layout”.
implementation 'com.google.android.material:material:1.2.0'
Note: Type this dependency line rather than copy and paste. Because due to copy and paste formatting or text style may be unaccepted if it is not matched with the required format.
Step 5: Working with the activity_main.xml file
After that, it is necessary to add the following views in a layout file of activity so open it. Here we use “activity_main.xml”.
- AppBarLayout
- ToolBar
- TabLayout
- ViewPager
Add the following code to the “activity_main.xml” file. Comments are added inside the code to understand the code in more detail.
XML
<?xml version="1.0" encoding="utf-8"?>
<!-- In order to use tabs, coordinator layout is useful-->
<androidx.coordinatorlayout.widget.CoordinatorLayout
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">
<!--This appbarlayout covers the toolbar and tablayout-->
<com.google.android.material.appbar.AppBarLayout
android:id="@+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#0F9D58"
android:theme="@style/AppTheme.AppBarOverlay">
<!--toolbar is one component which is necessary
because if we not use this then title is not shown
when project executed-->
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="@style/AppTheme.PopupOverlay" />
<!-- tablayout which contains which is
important to show tabs -->
<com.google.android.material.tabs.TabLayout
android:id="@+id/tab_tablayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabIndicatorColor="#FFF"
app:tabIndicatorHeight="3dp"
app:tabMode="fixed" />
</com.google.android.material.appbar.AppBarLayout>
<!-- view pager is used to open other fragment by using
left or right swip-->
<androidx.viewpager.widget.ViewPager
android:id="@+id/tab_viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="5dp"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
Step 6: Working with the MainActivity.kt file
After that, open “MainActivity.kt”. In this file, it is important to create the object of Toolbar, ViewPager, and TabLayout and use the “findViewById()” method to identify the view. Its syntax is shown below.
var object_name = findViewById<ViewName>(unique_id_assigned_to_view)
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 android.os.Bundle
import androidx.annotation.Nullable
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import androidx.viewpager.widget.ViewPager
import com.google.android.material.tabs.TabLayout
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Create the object of Toolbar, ViewPager and
// TabLayout and use “findViewById()” method*/
var tab_toolbar = findViewById<Toolbar>(R.id.toolbar)
var tab_viewpager = findViewById<ViewPager>(R.id.tab_viewpager)
var tab_tablayout = findViewById<TabLayout>(R.id.tab_tablayout)
// As we set NoActionBar as theme to this activity
// so when we run this project then this activity doesn't
// show title. And for this reason, we need to run
// setSupportActionBar method
setSupportActionBar(tab_toolbar)
setupViewPager(tab_viewpager)
// If we dont use setupWithViewPager() method then
// tabs are not used or shown when activity opened
tab_tablayout.setupWithViewPager(tab_viewpager)
}
// This function is used to add items in arraylist and assign
// the adapter to view pager
private fun setupViewPager(viewpager: ViewPager) {
var adapter: ViewPagerAdapter = ViewPagerAdapter(supportFragmentManager)
// LoginFragment is the name of Fragment and the Login
// is a title of tab
adapter.addFragment(LoginFragment(), "Login")
adapter.addFragment(SignupFragment(), "Signup")
// setting adapter to view pager.
viewpager.setAdapter(adapter)
}
// This "ViewPagerAdapter" class overrides functions which are
// necessary to get information about which item is selected
// by user, what is title for selected item and so on.*/
class ViewPagerAdapter : FragmentPagerAdapter {
// objects of arraylist. One is of Fragment type and
// another one is of String type.*/
private final var fragmentList1: ArrayList<Fragment> = ArrayList()
private final var fragmentTitleList1: ArrayList<String> = ArrayList()
// this is a secondary constructor of ViewPagerAdapter class.
public constructor(supportFragmentManager: FragmentManager)
: super(supportFragmentManager)
// returns which item is selected from arraylist of fragments.
override fun getItem(position: Int): Fragment {
return fragmentList1.get(position)
}
// returns which item is selected from arraylist of titles.
@Nullable
override fun getPageTitle(position: Int): CharSequence {
return fragmentTitleList1.get(position)
}
// returns the number of items present in arraylist.
override fun getCount(): Int {
return fragmentList1.size
}
// this function adds the fragment and title in 2 separate arraylist.
fun addFragment(fragment: Fragment, title: String) {
fragmentList1.add(fragment)
fragmentTitleList1.add(title)
}
}
}
Output
Similar Reads
How to Implement RecyclerView in a Fragment in Android?
In Android, a fragment is a modular section of a user interface that can be combined with other fragments to create a flexible and responsive application. Â A fragment represents a behavior or a portion of the user interface in an Activity, which can be reused in different activities or layouts. It h
12 min read
How to Implement onBackPressed() in Fragments in Android?
In Android, the Fragment is the part of the Activity that represents a portion of the User Interface(UI) on the screen. It is the modular section of the android activity that is very helpful in creating UI designs that are flexible in nature and auto-adjustable based on the device screen size. onBac
3 min read
How to Implement GridView Inside a Fragment in Android?
A GridView is a versatile and efficient widget that allows you to display items in a grid-like fashion, perfect for presenting images, icons, or any structured data. Fragments, on the other hand, are essential components for building flexible and modular user interfaces. They enable the creation of
5 min read
Android Image Slider using ViewPager in Kotlin
Image slider is seen in most e-commerce applications that display advertisements on the home screen. This slider displays the advertisement banners which users can slide to view the others. In this article, we will take a look at Implementing the image slider using ViewPager in Android using Kotlin.
5 min read
How to Implement findViewById in Fragments in Android?
Fragments represent a part of the app's UI which is reusable. Fragments are having its own layout, and lifecycle but must be hosted inside an activity to be visible. The activity becomes easier to modify if it consists of many fragments. A fragment can have multiple instances inside an activity. fin
3 min read
Implement Google Admob Banner Ads in Android using Kotlin
There are several ways to earn money from mobile applications such as selling products online through applications or simply displaying ads within applications. There are so many types of ads that we can display within our application. Google provides us a service known as Google Admob with the help
3 min read
How to Implement ViewPager with Dotsindicator in Android?
ViewPager in Android is a class that allows the user to flip left and right through pages of data. This class provides the functionality to flip pages in-app. It is a widget found in the support library. What are Dotsindicator? These are dots that help us to see which view is currently opened when w
4 min read
What is Flow in Kotlin and How to use it in Android Project?
To build an app asynchronously we have to use RxJava and it is also one of the most important topics in Android Development. But now in Kotlin Jetbrains came up with Flow API. With Flow in Kotlin now we can handle a stream of data sequentially. Flow is a stream processing API in Kotlin developed by
4 min read
Implement Universal Image Loader Library in Android using Kotlin
Universal Image Loader library is also referred to as (UIL). It is similar to Picasso and Glide which is used to load the images from the URL within our image view inside our android application. This image loading library has been created to provide a powerful, flexible, and customizable solution t
4 min read
How to Create an Android App That Moves a View Using Motion Sensors
A Motion Sensor in an android device detects movement and acceleration, and can be used for many purposes, including navigation, security, and user interaction. One of the most commonly used motion sensors in Android devices is the Accelerometer, which detects changes in movement and orientation. In
13 min read