TabLayout Tutorial With Example In Android Studio

In Android TabLayout is a new element introduced in Design Support library. It  provides horizontal layout to display tabs on the screen. We can display more screens in a single screen using tabs. We can quickly swipe between the tabs. TabLayout is basically view class required to be added into our layout(xml) for creating Sliding Tabs. We use different methods of TabLayout to create, add and manage the tabs.

TabLayout in Android

Special Note: TabLayout is used to display tabs on the screen. We can create sliding as well as non sliding tabs by using TabLayout. If we need simple tabs without sliding then we replace the layout with the fragment on tab selected listener event and if we need sliding tabs then we use Viewpager.


Basic TabLayout XML Code:

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

Important Methods Of TabLayout:

Let’s we discuss some important methods of TabLayout that may be called in order to manage the TabLayout.

1. newTab(): This method is used to create and return a new TabLayout.Tab.

Below we create a new tab and set the text and icon for the tab.

TabLayout   tabLayout = (TabLayout) findViewById(R.id.simpleTabLayout); // get the reference of TabLayout
TabLayout.Tab firstTab = tabLayout.newTab(); // Create a new Tab names
firstTab.setText("First Tab"); // set the Text for the first Tab
firstTab.setIcon(R.drawable.ic_launcher); // set an icon for the first tab

2. addTab(Tab tab): This method is used to add a tab in the TabLayout. By using this method we add the tab which we created using newTab() method in the TabLayout. The tab will be added at the end of the list and  If it is the first tab to be added then it will become the selected tab.

Below we firstly create a new tab and then add it in the TabLayout.

TabLayout   tabLayout = (TabLayout) findViewById(R.id.simpleTabLayout); // get the reference of TabLayout
TabLayout.Tab firstTab = tabLayout.newTab(); // Create a new Tab names "First Tab"
firstTab.setText("First Tab"); // set the Text for the first Tab
firstTab.setIcon(R.drawable.ic_launcher); // set an icon for the first tab
tabLayout.addTab(firstTab); // add  the tab to the TabLayout

3. addTab(Tab tab, boolean setSelected): This method is used to add a tab in the TabLayout and set the state for the tab. By using this method we add the tab which we created using newTab() method in the TabLayout. In this method we also set the state of the tab whether it is selected or not.

Below we firstly create a new tab and then add it in the TabLayout and set the true value for setSelected parameter that makes it selectable.

TabLayout   tabLayout = (TabLayout) findViewById(R.id.simpleTabLayout); // get the reference of TabLayout
TabLayout.Tab firstTab = tabLayout.newTab(); // Create a new Tab names "First Tab"
firstTab.setText("First Tab"); // set the Text for the first Tab
firstTab.setIcon(R.drawable.ic_launcher); // set an icon for the first tab
tabLayout.addTab(firstTab,true); // add  the tab in the TabLayout and makes it selectable

4. addTab(Tab tab, int position): This method is used to add a tab in the TabLayout and set the state for the tab. By using this method we add the tab which we created using newTab() method in the TabLayout. The tab will be inserted at the given position. If it is the first tab to be added then it will become the selected tab.

Below we firstly create a new tab and then add it in the TabLayout at a specific position.

TabLayout   tabLayout = (TabLayout) findViewById(R.id.simpleTabLayout); // get the reference of TabLayout
TabLayout.Tab firstTab = tabLayout.newTab(); // Create a new Tab names "First Tab"
firstTab.setText("First Tab"); // set the Text for the first Tab
firstTab.setIcon(R.drawable.ic_launcher); // set an icon for the first tab
tabLayout.addTab(firstTab,2); // add  the tab in the TabLayout at specific position

5. addTab(Tab tab, int position, boolean setSelected): This method is used to add a tab at a specific position and set the state of the tab. By using this method we add the tab which we created using newTab() method in the TabLayout. The tab will be inserted at  the defined  position and a Boolean value used to set the state of the tab. True value is used to make the tab selectable.

Below we firstly create a tab and then add it in the TabLayout at a specific position and we also set true value to make the tab selectable.

TabLayout   tabLayout = (TabLayout) findViewById(R.id.simpleTabLayout); // get the reference of TabLayout
TabLayout.Tab firstTab = tabLayout.newTab(); // Create a new Tab names "First Tab"
firstTab.setText("First Tab"); // set the Text for the first Tab
firstTab.setIcon(R.drawable.ic_launcher); // set an icon for the first tab
tabLayout.addTab(firstTab,2,true); // add  the tab at specified position in the TabLayout and makes it selectable

6. getSelectedTabPosition(): This method is used to get the position of the current selected tab. This method returns an int type value for the position of the selected tab. It returns -1 if there isn’t a selected tab.

Below we get the current selected tab position.

TabLayout   tabLayout = (TabLayout) findViewById(R.id.simpleTabLayout); // get the reference of TabLayout
int selectedTabPosition = tabLayout.getSelectedTabPosition(); // get the position for the current selected tab

7. getTabAt(int index): This method is used to get the tab at the specified index. This method returns TabLayout.Tab.

Below we get the tab at 1th index.

TabLayout tabLayout = (TabLayout) findViewById(R.id.simpleTabLayout); // get the reference of TabLayout
TabLayout.Tab tab = tabLayout.getTabAt(1); //  get the tab at 1th in index

8. getTabCount(): This method is used to get the number of tabs currently registered with the action bar. This method returns an int type value for the number of total tabs.

Below we get the total number of tabs currently registered with the action bar.

TabLayout tabLayout = (TabLayout) findViewById(R.id.simpleTabLayout); // get the reference of TabLayout
int tabCount= tabLayout.getTabCount(); // get the total number of tabs currently registered with the action bar.

9. setTabGravity(int gravity): This method is used to set the gravity to use when laying out the tabs.

Below we set the gravity for the tabs.

TabLayout tabLayout = (TabLayout) findViewById(R.id.simpleTabLayout); // get the reference of TabLayout
tabLayout.setTabGravity(TabLayout.GRAVITY_CENTER); // set the gravity to use when laying out the tabs.

10. getTabGravity(): This method is used to get the current gravity used for laying out tabs. This method returns the gravity which we set using setTabGravity(int gravity) method.

Below we firstly set the gravity and then get the current gravity used for laying out tabs.

TabLayout tabLayout = (TabLayout) findViewById(R.id.simpleTabLayout); // get the reference of TabLayout
tabLayout.setTabGravity(TabLayout.GRAVITY_CENTER); // set the gravity to use when laying out the tabs.
int gravity=tabLayout.getTabGravity(); // get the current gravity used for laying out tabs

11. setTabMode(int mode): This method is used to set the behavior mode for the Tabs in this layout. The valid input options are:

MODE_FIXED:  Fixed tabs display all tabs concurrently and are best used with content that benefits from quick pivots between tabs.

MODE_SCROLLABLE: Scrollable tabs display a subset of tabs at any given moment and it can contain longer tab labels and a larger number of tabs. They are best used for browsing contexts in touch interfaces when users don’t need to directly compare the tab labels. This mode is commonly used with a ViewPager.

Below we set the behaviour mode for the tabs.

TabLayout tabLayout = (TabLayout) findViewById(R.id.simpleTabLayout); // get the reference of TabLayout
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE); // set the behaviour mode for the tabs

12. getTabMode(): This method is used to get the current mode of TabLayout. This method returns an int type value which we set using setTabMode(int mode) method.

Below we firstly set the tab mode and then get the current mode of the TabLayout.

TabLayout tabLayout = (TabLayout) findViewById(R.id.simpleTabLayout); // get the reference of TabLayout
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE); // set the behaviour mode for the tabs
int mode=tabLayout.getTabMode(); // get the current mode of the TabLayout

13. setTabTextColors(int normalColor, int selectedColor): This method is used to set the text colors for the different states (normal, selected) of the tabs.

Below we set the tab text colors for the both states of the tab.

TabLayout tabLayout = (TabLayout) findViewById(R.id.simpleTabLayout); // get the reference of TabLayout
tabLayout.setTabTextColors(Color.RED,Color.WHITE); // set the tab text colors for the both states of the tab.

14. getTabTextColors(): This method is used to get the text colors for the different states (normal, selected) of the tabs. This method returns the text color which we set using setTabTextColors(int normalColor, int selectedColor) method.

Below we firstly set the text colors and then get the text colors for the both states of the tab.

TabLayout tabLayout = (TabLayout) findViewById(R.id.simpleTabLayout); // get the reference of TabLayout
tabLayout.setTabTextColors(Color.RED,Color.WHITE); // set the tab text colors for the both states of the tab.
ColorStateList colorStateList=tabLayout.getTabTextColors(); // get the text colors for the both states of the tab

15. removeAllTabs(): This method is used to remove all tabs from the action bar and deselect the current tab.

Below we remove all the tabs from the action bar and deselect the current tab.

TabLayout tabLayout = (TabLayout) findViewById(R.id.simpleTabLayout); // get the reference of TabLayout
tabLayout.removeAllTabs(); // remove all the tabs from the action bar and deselect the current tab

16. setOnTabSelectedListener(OnTabSelectedListener listener): This method is used to add a  listener that will be invoked when tab selection changes.

Below we show how to use addOnTabSelectedListener of TabLayout.

TabLayout tabLayout = (TabLayout) findViewById(R.id.simpleTabLayout); // get the reference of TabLayout
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
// called when tab selected
}

@Override
public void onTabUnselected(TabLayout.Tab tab) {
// called when tab unselected
}

@Override
public void onTabReselected(TabLayout.Tab tab) {
// called when a tab is reselected
}
});

17. removeTab(Tab tab): This method is used to remove a tab from the layout. In this method we pass the TabLayout.Tab object to remove the tab from the layout. If the removed tab was selected then it will be automatically deselected and another tab will be selected if present in the TabLayout.

Below we firstly create and add a tab and then remove it from the TabLayout.

TabLayout tabLayout = (TabLayout) findViewById(R.id.simpleTabLayout); // get the reference of TabLayout
TabLayout.Tab firstTab = tabLayout.newTab(); // Create a new Tab names "First Tab"
firstTab.setText("First Tab"); // set the Text for the first Tab
firstTab.setIcon(R.drawable.ic_launcher); // set an icon for the first tab
tabLayout.addTab(firstTab); // add  the tab at in the TabLayout
tabLayout.removeTab(firstTab); // remove the tab from the TabLayout

18. removeTabAt(int position): This method is used to remove a tab from the layout. In this method we pass the position of the tab that we want to remove from the layout. If the removed tab was selected then it will be automatically deselected and another tab will be selected if present in the TabLayout.

Below we remove the tab from a specified position of TabLayout.

TabLayout tabLayout = (TabLayout) findViewById(R.id.simpleTabLayout); // get the reference of TabLayout
tabLayout.removeTabAt(1); // remove the tab from a specified position of TabLayout

19. setSelectedTabIndicatorColor(int color): This method is used to set the tab indicator’s color for the currently selected tab.

Below we set the red color for the selected tab indicator.

TabLayout tabLayout = (TabLayout) findViewById(R.id.simpleTabLayout); // get the reference of TabLayout
tabLayout.setSelectedTabIndicatorColor(Color.RED); // set the red color for the selected tab indicator.

20. setSelectedTabIndicatorHeight(int height): This method is used to set the tab indicator’s height for the currently selected tab.

Below we set the height for the selected tab’s indicator.

TabLayout tabLayout = (TabLayout) findViewById(R.id.simpleTabLayout); // get the reference of TabLayout
tabLayout.setSelectedTabIndicatorHeight(2); // set the height for the selected tab’s indicator

21. setupWithViewPager(ViewPager viewPager): This method is used for setting up the TabLayout with ViewPager. ViewPager is mainly used for creating Sliding tabs.

Below we set the TabLayout with the ViewPager.

ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager); // get the reference of ViewPager
TabLayout tabLayout = (TabLayout) findViewById(R.id.simpleTabLayout); // get the reference of TabLayout
tabLayout.setupWithViewPager(viewPager); // set the TabLayout with the ViewPager.

Attributes of TabLayout:

Now let’s we discuss some common attributes of a TabLayout that helps us to configure it in our layout (xml).

1. id: id attribute is used to uniquely identify a TabLayout.

2. support.design:tabBackground: This attribute is used to set the background of the tabs. We can set a color or drawable in the background of tabs.

Below we set the Black color for the background of the tabs.

<android.support.design.widget.TabLayout
android:id="@+id/simpleTabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabBackground="@android:color/darker_gray" /><!-- set the Black color for the background of the tabs.-->

3. support.design:tabGravity: This attribute is used to set the gravity to use when laying out the tabs. We can also set gravity programmatically means in java class using setTabGravity(int gravity) method.

Below we set the gravity for the tabs.

<android.support.design.widget.TabLayout
android:id="@+id/simpleTabLayout "
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="fill" /><!-- set the gravity for the tabs.-->

4. support.design:tabIndicatorColor: This attribute is used to set the Color of the indicator used to show the currently selected tab. We can also set color programmatically means in java class using setSelectedTabIndicatorColor(int color) method.

Below we set the red color for the selected tab indicator

<android.support.design.widget.TabLayout
android:id="@+id/simpleTabLayout "
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabIndicatorColor="#f00" /><!-- set the red color for the selected tab indicator.-->

5. support.design:tabIndicatorHeight: This attribute is used to set the height of the indicator used to show the currently selected tab. We can also set height programmatically means in java class using setSelectedTabIndicatorHeight(int height) method.

Below we set the height for the selected tab’s indicator.

<android.support.design.widget.TabLayout
android:id="@+id/simpleTabLayout "
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabIndicatorHeight="2dp" />
<!-- set the height for the selected tab’s indicator -->

6. support.design:tabMaxWidth: This attribute is used to set the maximum width for the tabs.

Below we set the maximum width value for the  tabs.

<android.support.design.widget.TabLayout
android:id="@+id/simpleTabLayout "
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMaxWidth="100dp" />
<!-- set the maximum width value for the  tabs. -->

7. support.design:tabMinWidth: This attribute is used to set the minimum width for the tabs.

Below we set the minimum width value for the tabs.

<android.support.design.widget.TabLayout
android:id="@+id/simpleTabLayout "
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMinWidth="50dp" />
<!-- set the minimum width value for the tabs  -->

8. support.design:tabMode: This attribute is used to set the behavior mode for the Tabs in this layout. We can also set the mode programmatically means in java class using setTabMode(int mode) method.

Below we set the behaviour mode for the tabs.

<android.support.design.widget.TabLayout
android:id="@+id/simpleTabLayout "
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed" />
<!-- set the behaviour mode for the tabs  -->

9. support.design:tabPadding: This attribute is used to set the padding along all edges of tabs.

android.support.design:tabPaddingBottom: Set padding along the bottom edge of the tabs.

android.support.design:tabPaddingEnd: Set padding along the end edge of the tabs.

android.support.design:tabPaddingStart: Set padding along the start edge of the tabs.

android.support.design:tabPaddingTop: Set padding along the top edge of the tabs.

Below we set the padding along all edges of the tabs.

<android.support.design.widget.TabLayout
android:id="@+id/simpleTabLayout "
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabPadding="5dp" />
<!-- set the padding along all edges of the tabs  -->

10. support.design:tabSelectedTextColor: This attribute is used to set the text color to be applied to the currently selected tab. We can also set this programmatically using setTabTextColors(int normalColor, int selectedColor) method.

Below we set the text color for the selected tab.

<android.support.design.widget.TabLayout
android:id="@+id/simpleTabLayout "
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabSelectedTextColor="#fff" />
<!-- set the text color for the selected tab.  -->

11. support.design:tabTextColor: This method is used to set the default text color to be applied to tabs. . We can also set this programmatically using setTabTextColors(int normalColor, int selectedColor) method.

Below we set the default text color for the tabs.

<android.support.design.widget.TabLayout
android:id="@+id/simpleTabLayout "
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabTextColor="#f00" />
<!-- set red as default text color for the text of tabs  -->

TabLayout Example In Android Studio:

Example 1 of TabLayout:

Below is the first example of TabLayout in which we display three non-sliding tabs. In this example we define a TabLayout and a FrameLayout in our xml file. In this example we create and add 3 tabs in the TabLayout with the help of different methods of TabLayout. After that we implement setOnTabSelectedListener event and replace the FrameLayout with the fragment’s according to selected tab.

Download Code

TabLayout Example in Android Studio

Step 1: Create a new project and name it TabLayoutExample

Step 2: Open build.gradle and add Design support library dependency.

apply plugin: 'com.android.application'

android {
compileSdkVersion 23
buildToolsVersion "23.0.2"

defaultConfig {
applicationId "com.abhiandroid.tablayoutexample"
minSdkVersion 15
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:23.1.0'
compile 'com.android.support:design:23.1.0' // design support library
}

Step 3:  Open res -> layout ->activity_main.xml (or) main.xml and add following code:

In this step we add the code for displaying TabLayout and ViewPager in our xml file.

<LinearLayout 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"
android:orientation="vertical"
tools:context=".MainActivity">

<android.support.design.widget.TabLayout
android:id="@+id/simpleTabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabBackground="@android:color/darker_gray"
app:tabIndicatorColor="#f00"
app:tabSelectedTextColor="#f00"
app:tabTextColor="#000" />

<FrameLayout
android:id="@+id/simpleFrameLayout"
android:layout_width="match_parent"
android:layout_height="match_parent" />

</LinearLayout>

Step4: Open   src -> package -> MainActivity.java

In this step we open MainActivity and add the code for initiate the FrameLayout and TabLayout.  After that we create and add 3 tabs in the TabLayout. Finally  we implement setOnTabSelectedListener event and replace the FrameLayout with the fragment’s according to selected tab.

package com.abhiandroid.tablayoutexample;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.widget.FrameLayout;

public class MainActivity extends AppCompatActivity {

FrameLayout simpleFrameLayout;
TabLayout tabLayout;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get the reference of FrameLayout and TabLayout
simpleFrameLayout = (FrameLayout) findViewById(R.id.simpleFrameLayout);
tabLayout = (TabLayout) findViewById(R.id.simpleTabLayout);
// Create a new Tab named "First"
TabLayout.Tab firstTab = tabLayout.newTab();
firstTab.setText("First"); // set the Text for the first Tab
firstTab.setIcon(R.drawable.ic_launcher); // set an icon for the
// first tab
tabLayout.addTab(firstTab); // add  the tab at in the TabLayout
// Create a new Tab named "Second"
TabLayout.Tab secondTab = tabLayout.newTab();
secondTab.setText("Second"); // set the Text for the second Tab
secondTab.setIcon(R.drawable.ic_launcher); // set an icon for the second tab
tabLayout.addTab(secondTab); // add  the tab  in the TabLayout
// Create a new Tab named "Third"
TabLayout.Tab thirdTab = tabLayout.newTab();
thirdTab.setText("Third"); // set the Text for the first Tab
thirdTab.setIcon(R.drawable.ic_launcher); // set an icon for the first tab
tabLayout.addTab(thirdTab); // add  the tab at in the TabLayout


// perform setOnTabSelectedListener event on TabLayout
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
// get the current selected tab's position and replace the fragment accordingly
Fragment fragment = null;
switch (tab.getPosition()) {
case 0:
fragment = new FirstFragment();
break;
case 1:
fragment = new SecondFragment();
break;
case 2:
fragment = new ThirdFragment();
break;
}
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.simpleFrameLayout, fragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
}

@Override
public void onTabUnselected(TabLayout.Tab tab) {

}

@Override
public void onTabReselected(TabLayout.Tab tab) {

}
});
}
}

Step 5: Now we need 3 fragments and 3 xml layouts for three tabs. So create three fragments by right click on your package folder and create classes and name them as FirstFragment, SecondFragment and ThirdFragment and add the following code respectively.

FirstFragment.class

package com.abhiandroid.tablayoutexample;

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

public class FirstFragment extends Fragment {

public FirstFragment() {
// Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_first, container, false);
}

}

SecondFragment.class

package com.abhiandroid.tablayoutexample;

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

public class SecondFragment extends Fragment {

public SecondFragment() {
// Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_second, container, false);
}

}

ThirdFragment.class

package com.abhiandroid.tablayoutexample;

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

public class ThirdFragment extends Fragment {

public ThirdFragment() {
// Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_third, container, false);
}

}

Step 6:  Now create 3 xml layouts by right clicking on res/layout -> New -> Layout Resource File and name them as fragment_first, fragment_second and fragment_third and add the following code in respective files.

Here we will design the basic simple UI for all the three tabs.

fragment_first.xml

<RelativeLayout 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="info.androidhive.materialtabs.fragments.OneFragment">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="First Fragment"
android:textSize="40dp"
android:textStyle="bold" />

</RelativeLayout>

fragment_second.xml

<RelativeLayout 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="info.androidhive.materialtabs.fragments.OneFragment">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Second Fragment"
android:textSize="40dp"
android:textStyle="bold" />

</RelativeLayout>

fragment_third.xml

<RelativeLayout 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="info.androidhive.materialtabs.fragments.OneFragment">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Third Fragment"
android:textSize="40dp"
android:textStyle="bold" />

</RelativeLayout>

Example 2 of TabLayout Using ViewPager:

Below is the example of TabLayout in which we display sliding tabs with the help of ViewPager. In this example we define a TabLayout and a ViewPager in our xml file. In this example we create and add 3 tabs in the TabLayout with the help of different methods of TabLayout. After that we create a PagerAdapter to set up the TabLayout with ViewPager.

Download Code

TabLayout Example in Android Studio

Step 1: Create a new project and name it TabLayoutExample

Step 2: Open build.gradle and add Design support library dependency.

apply plugin: 'com.android.application'

android {
compileSdkVersion 23
buildToolsVersion "23.0.2"

defaultConfig {
applicationId "com.abhiandroid.tablayoutexample"
minSdkVersion 15
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:23.1.0'
compile 'com.android.support:design:23.1.0' // design support library
}

Step 3:  Open res -> layout ->activity_main.xml (or) main.xml and add following code:

<LinearLayout 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"
android:orientation="vertical"
tools:context=".MainActivity">

<android.support.design.widget.TabLayout
android:id="@+id/simpleTabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabBackground="@android:color/darker_gray"
app:tabIndicatorColor="#f00"
app:tabSelectedTextColor="#f00"
app:tabTextColor="#000" />


<android.support.v4.view.ViewPager
android:id="@+id/simpleViewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</LinearLayout>

Step 4: Open   src -> package -> MainActivity.java

In this step we open MainActivity and add the code for initiate the ViewPager and TabLayout.  After that we create and add 3 tabs in the TabLayout. Finally we set an Adapter named  PagerAdapter to set up the TabLayout with ViewPager.

package com.abhiandroid.tablayoutexample;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

ViewPager simpleViewPager;
TabLayout tabLayout;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get the reference of ViewPager and TabLayout
simpleViewPager = (ViewPager) findViewById(R.id.simpleViewPager);
tabLayout = (TabLayout) findViewById(R.id.simpleTabLayout);
// Create a new Tab named "First"
TabLayout.Tab firstTab = tabLayout.newTab();
firstTab.setText("First"); // set the Text for the first Tab
firstTab.setIcon(R.drawable.ic_launcher); // set an icon for the
// first tab
tabLayout.addTab(firstTab); // add  the tab at in the TabLayout
// Create a new Tab named "Second"
TabLayout.Tab secondTab = tabLayout.newTab();
secondTab.setText("Second"); // set the Text for the second Tab
secondTab.setIcon(R.drawable.ic_launcher); // set an icon for the second tab
tabLayout.addTab(secondTab); // add  the tab  in the TabLayout
// Create a new Tab named "Third"
TabLayout.Tab thirdTab = tabLayout.newTab();
thirdTab.setText("Third"); // set the Text for the first Tab
thirdTab.setIcon(R.drawable.ic_launcher); // set an icon for the first tab
tabLayout.addTab(thirdTab); // add  the tab at in the TabLayout

PagerAdapter adapter = new PagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
simpleViewPager.setAdapter(adapter);
// addOnPageChangeListener event change the tab on slide
simpleViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
}
}

Step 5: Create a new Class named PagerAdapter and extend FragmentStatePagerAdapter in the class. In this step we create a PagerAdapter class and extends FragmentStatePagerAdapter In the class for setting the TabLayout with the ViewPager.

package com.abhiandroid.tablayoutexample;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;

public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;

public PagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}

@Override
public Fragment getItem(int position) {

switch (position) {
case 0:
FirstFragment tab1 = new FirstFragment();
return tab1;
case 1:
SecondFragment tab2 = new SecondFragment();
return tab2;
case 2:
ThirdFragment tab3 = new ThirdFragment();
return tab3;
default:
return null;
}
}

@Override
public int getCount() {
return mNumOfTabs;
}
}

Step 6: Now we need 3 fragments and 3 xml layouts for three tabs. So create three fragments by right click on your package folder and create classes and name them as FirstFragment, SecondFragment and ThirdFragment and add the following code respectively.

FirstFragment.class

package com.abhiandroid.tablayoutexample;

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

public class FirstFragment extends Fragment {

public FirstFragment() {
// Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_first, container, false);
}

}

SecondFragment.class

package com.abhiandroid.tablayoutexample;

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

public class SecondFragment extends Fragment {

public SecondFragment() {
// Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_second, container, false);
}

}

ThirdFragment.class

package com.abhiandroid.tablayoutexample;

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

public class ThirdFragment extends Fragment {

public ThirdFragment() {
// Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_third, container, false);
}

}

Step 7:  Now create 3 xml layouts by right clicking on res/layout -> New -> Layout Resource File and name them as fragment_first, fragment_second and fragment_third and add the following code in respective files.

Here we will design the basic simple UI for all the three tabs.

fragment_first.xml

<RelativeLayout 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="info.androidhive.materialtabs.fragments.OneFragment">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="First Fragment"
android:textSize="40dp"
android:textStyle="bold" />

</RelativeLayout>

fragment_second.xml

<RelativeLayout 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="info.androidhive.materialtabs.fragments.OneFragment">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Second Fragment"
android:textSize="40dp"
android:textStyle="bold" />

</RelativeLayout>

fragment_third.xml

<RelativeLayout 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="info.androidhive.materialtabs.fragments.OneFragment">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Third Fragment"
android:textSize="40dp"
android:textStyle="bold" />

</RelativeLayout>

Download This FREE eBook

This free eBook will help you master the learning of Android Material Design in Android Studio!

15 thoughts on “TabLayout Tutorial With Example In Android Studio”

  1. I was struggling mightily with how to change fragments in response to a tab selection. This helped a lot. Thanks!

  2. This line needs to be corrected to match the project path: tools:context=”info.androidhive.materialtabs.fragments.OneFragment”.

    Also, there’s no “OneFragment” XML file.

  3. Very useful tutorial on tabs but it really makes programming with class objects seem so much clearer and simpler. Good.

  4. Great tutorial, although i already have my code which is similar to that of the second example. My question is i have an activity that has a 5 buttons for selecting 5 different categories. These categories are in a different activity which holds the tabylayout and 5 fragments layouts. How do i get to a specific tab when a button specific to the tab is clicked.

  5. Hi
    I have download the two examples
    The first one work fine but the second don’t
    It doesn’t load the fragments when pressing on the TabLayout
    Can you check it out please?

    1. Add this on bottom of MainActivity after simpleViewPager.addOnPageChangeListener.

      tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener()
      {
      @Override
      public void onTabSelected(TabLayout.Tab tabSelected)
      {
      simpleViewPager.setCurrentItem(tabSelected.getPosition());
      }

      @Override
      public void onTabUnselected(TabLayout.Tab tabSelected){}

      @Override
      public void onTabReselected(TabLayout.Tab tabSelected){

      }
      });

  6. Hi friend, the tutorial is rely great thanks a lot.
    I wish to make an android app using tabbed layout with one of the tabs having a data entry form that submits data to the local host or remote server database of my MySQL (but strictly the form must be a sliding tabbed activity or fragment)

  7. I dont know How? but ,
    tabLayout.setTextColor(),tabLayout.setSelectedTextColor()…and tabLayout.addtab(tab,state) does not works for me .