Select Page

TabLayout provides a horizontal layout to display tabs.It makes it easy to implement scrolling tabs for your ViewPager.TabLayout providing the ability to switch between tabs by clicking on the according tab label and an indication of the current tab.

In this post, I will describe the basic stuff of the TabLayout and how to implement this view into your application.

TabItem is a special ‘view’ which allows you to declare tab items for a TabLayout within a layout. You can add tabs using TabItem(in XML) and tablayout.addTab(tabItem);(in java).

To begin with, you need to add the TabLayout to your layout:


There are several attributes here that we can set to adjust the appearance.

  • app:tabMode=”fixed”  : view’s width divided equally for all tabs, and shows all tabs concurrently.
  • app:tabMode=”scrollable”  : view’s width divided based on the length of the title and can scroll horizontally.
  • app:tabGravity=”fill” : distribute all available space between individual tabs.
  • app:tabGravity=”center” : position tabs in the center of the TabLayout.
  • app:tabBackground : set the background of the Tabs
  • app:tabIndicatorColor : set the color of the indicator used to show the currently selected tab.
  • app:tabIndicatorHeight : set the height of the indicator.
  • app:tabSelectedTextColor : set the text color of the currently selected tab.
  • app:tabTextColor : set the text color of the currently selected tab.


You need to know some of the native methods used in TabLayout.

  • addTab : Add a tab to tablayout.
  • getSelectedTabPosition :  returns the position of the current selected tab.
  • getTabAt :  returns the Tab of the specified position.
  • getTabCount : returns the number of tabs currently registered .
  • newTab : create and return a tab.
  • removeTab : remove a tab from the tablayout.
  • setupWithViewPager : easy to set up a viewpager to the tablayout.

You can track the tab selection by the user using addOnPageChangeListener 

tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
public void onTabSelected(TabLayout.Tab tab) {
// while selecting the tab
public void onTabUnselected(TabLayout.Tab tab) {
// while unselect the Tab
public void onTabReselected(TabLayout.Tab tab) {
// while reselect the Tab

You can use ViewPager with this TabLayout easily for implementing swipeable tabs feature in your application. It deserves a separate blog post. I’m planning to write one soon. Keep watching this space for updates.


Jaison Fernando

Android Developer at NFN Labs