Getting Started with Tabs in Android — Kotlin

Jaz Allibhai
4 min readMar 2, 2018

--

In this short tutorial, I’ll go over how to get started with setting up TabLayout in your Android app.

There are three main steps to take in order to get started with tabs in your app: setting up the FragmentPagerAdapter, the fragments to be displayed in each tab, and the ViewPager.

Start off by opening a new project with an empty activity.

We will need to add the dependency for tabs in our build.gradle file. Add the following dependency:

implementation ‘com.android.support:design:26.1.0’

(change the version number in the dependency to whichever appcompat version you’re running).

Create a new Kotlin class called MyPagerAdapter.

In MyPagerAdapter.kt

The MyPagerAdapter class will take in a FragmentManager as a parameter. Extend the FragmentPagerAdapter class and pass in the FragmentManager.

Override the two necessary functions for the FragmentPagerAdapter class: getCount() and getItem().

In getCount, we will return the number of tabs we intend to have. We will have 3 tabs, so we can simply return 3.

In getItem, we will return the fragment that we want to be displayed in each tab. The count starts from 0, so in our when clause, we will have 3 options: 0, 1, or else. For now, name the fragments “FirstFragment()”, SecondFragment()”, and “ThirdFragment()”. We will create these fragments shortly.

Override a third function called getPageTitle(). As the name suggests, this function will be where we give our tabs titles. To keep things simple, name the tabs “First Tab”, “Second Tab”, and “Third Tab”.

MyPagerAdapter.kt

import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentPagerAdapter

class MyPagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {

override fun getItem(position: Int): Fragment {
return when (position) {
0 -> {
FirstFragment()
}
1 -> SecondFragment()
else -> {
return ThirdFragment()
}
}
}

override fun getCount(): Int {
return 3
}

override fun getPageTitle(position: Int): CharSequence {
return when (position) {
0 -> "First Tab"
1 -> "Second Tab"
else
-> {
return "Third Tab"
}
}
}
}

Now we will go ahead and create the 3 fragments. Create 3 new blank fragments and name them “FirstFragment”, “SecondFragment” and “ThirdFragment” to match our names in the MyPagerAdapter class. When creating each new fragment, keep “Create layout XML?” checked and uncheck “Include fragment factory methods?” and “Include interface callbacks?”.

In each of the layout files for the new fragments, add the text “First tab”, “Second tab” or “Third Tab” to the corresponding TextViews and increase the text size in each TextView to 40sp. This will give us an easy way to see that the correct fragment appears when we go to test the app.

For brevity, I’ll only post the code for one fragment in this post (the full source code is available here).

FirstFragment.kt

import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup


/**
* A simple
[Fragment] subclass.
*/
class FirstFragment : Fragment() {

override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
return inflater!!.inflate(R.layout.fragment_first, container, false)
}
}

fragment_first.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="me.eijaz.tabstutorial.FirstFragment"
>

<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="First tab"
android:textSize="40sp"
/>

</FrameLayout>

In activity_main.xml

Get rid of the default TextView.

Add a TabLayout with an id of “tabs_main”. Add an app:tabMode attribute and set it to “fixed”. We only have 3 tabs so we do not need to have a scrollable TabLayout.

Add a ViewPager with an id of “viewpager_main” and constrain it to the bottom of the TabLayout.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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="me.eijaz.tabstutorial.MainActivity"
>

<android.support.design.widget.TabLayout
android:id="@+id/tabs_main"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"
/>

<android.support.v4.view.ViewPager
android:id="@+id/viewpager_main"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@+id/tabs_main"
/>

</android.support.constraint.ConstraintLayout>

In MainActivity.kt

Attach MyPagerAdapter to your ViewPager and link the ViewPager with the TabLayout. This will ensure that the correct fragments are attached to their corresponding tabs.

MainActivity.kt

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val fragmentAdapter = MyPagerAdapter(supportFragmentManager)
viewpager_main.adapter = fragmentAdapter

tabs_main.setupWithViewPager(viewpager_main)
}
}

That’s it! Now run the project! Swipe through the tabs to make sure the TabLayout is working correctly and the correct fragments have been attached to each tab.

The full source code is available here.

Thanks for reading! Too keep up to date with my journey as an Android developer, follow me on Twitter.

--

--