How to Implement Tabs, ViewPager and Fragment in Android using Kotlin?

30 Jun, 2021
In some android apps, Tabs are used, which allows developers to combine multiple tasks (operations) on a single activity. On another side, it provides a different look to that app. It is also possible to provide different feel like left and right swipe by using ViewPager. And to implement this topic, few terms are required such as ViewPager, Fragments, and TabLayout. For practice purposes, Kotlin programming language is used in this article.
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 feature to show another fragment.
Fragments: This is a part of the Activity. This view is necessary, to do multiple tasks on a single activity. The Fragment also makes use of layout file which contains view/s as per need.
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: 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.
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.Bundleimport android.view.LayoutInflaterimport android.view.Viewimport android.view.ViewGroupimport androidx.fragment.app.Fragment // Here ":" symbol is indicate that LoginFragment// is child class of Fragment Classclass 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.Bundleimport android.view.LayoutInflaterimport android.view.Viewimport android.view.ViewGroupimport androidx.fragment.app.Fragment // Here ":" symbol is indicate that SignupFragment// is child class of Fragment Classclass 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.
 
Step 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.Bundleimport androidx.annotation.Nullableimport androidx.appcompat.app.AppCompatActivityimport androidx.appcompat.widget.Toolbarimport androidx.fragment.app.Fragmentimport androidx.fragment.app.FragmentManagerimport androidx.fragment.app.FragmentPagerAdapterimport androidx.viewpager.widget.ViewPagerimport 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)        }    }}
 
 
 
arorakashish0911
android
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.