Open In App

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

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.

What are TabLayout, ViewPager, and Fragment?

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




<?xml version="1.0" encoding="utf-8"?>
<!-- This linear layout is used to show elements
     in vertical or in horizontal linear manner -->
<LinearLayout
    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>

 
 

 




<?xml version="1.0" encoding="utf-8"?>
<!-- This linear layout is used to show elements
     in vertical or in horizontal linear manner -->
<LinearLayout
    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>

 

 

 

 




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
}

 

 

 

 

 




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

 

 




<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>
     
    <!-- 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>

 
 

 

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”.

 

 

Add the following code to the “activity_main.xml” file. Comments are added inside the code to understand the code in more detail.

 




<?xml version="1.0" encoding="utf-8"?>
 
<!-- In order to use tabs, coordinator layout is useful-->
<androidx.coordinatorlayout.widget.CoordinatorLayout
    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.

 




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

 


Article Tags :