In this tutorial I am going to show you how to implement Tab Layout in the Android Application using ViewPager and Fragments. You can Swipe between the Tabs you added in the Application. In this tutorial we are going to create a Android Application with three Tabs Android, iOS, Windows.

Creating Project

Open Eclipse and create a new Project by File->New->Android Application Project. Give the package name as com.learn2crack.tab and select Theme as Holo Light with Dark Action Bar. Name the Main Activity as MainActivity and Main layout as activity_main.

android tab layout

Download Complete Project

Creating Layout

The Main Layout activity_main contains ViewPager which is used to swipe between views.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

The layout android_frag.xml is for Android Tab fragment.

android_frag.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="50sp"/>

</LinearLayout>

The layout ios_frag.xml is for iOS Tab fragment.

ios_frag.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="50sp"/>

</LinearLayout>

The layout windows_frag.xml is for Windows Tab fragment.

windows_frag.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="50sp"/>

</LinearLayout>

Creating Classes

Before proceeding to MainActivity.java class we must create a new class TabPagerAdapter.java which is used to display the tab fragments. It is extended to FragmentStatePagerAdapter.

TabPagerAdapter.java

package com.learn2crack.tab;

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

public class TabPagerAdapter extends FragmentStatePagerAdapter {
    public TabPagerAdapter(FragmentManager fm) {
		super(fm);
		// TODO Auto-generated constructor stub
	}

	@Override
	public Fragment getItem(int i) {
		switch (i) {
        case 0:
            //Fragement for Android Tab
            return new Android();
        case 1:
           //Fragment for Ios Tab
            return new Ios();
        case 2:
            //Fragment for Windows Tab
            return new Windows();
        }
		return null;

	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return 3; //No of Tabs
	}

    }

The next is to create Android fragment class which is extended to Fragment. It has a TextView to display Text.

Android.java

package com.learn2crack.tab;

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

public class Android extends Fragment {
	@Override
	    public View onCreateView(LayoutInflater inflater, ViewGroup container,
	            Bundle savedInstanceState) {

	        View android = inflater.inflate(R.layout.android_frag, container, false);
	        ((TextView)android.findViewById(R.id.textView)).setText("Android");
	        return android;
}}

Then Ios fragment class which is also extended to Fragment. It has a TextView to display Text.

Ios.java

package com.learn2crack.tab;

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

public class Ios extends Fragment {
	 @Override
	    public View onCreateView(LayoutInflater inflater, ViewGroup container,
	            Bundle savedInstanceState) {

	        View ios = inflater.inflate(R.layout.ios_frag, container, false);
	        ((TextView)ios.findViewById(R.id.textView)).setText("iOS");
	        return ios;
}}

Then Windows fragment class which is also extended to Fragment.

Windows.java

package com.learn2crack.tab;

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

public class Windows extends Fragment {
	 @Override
	    public View onCreateView(LayoutInflater inflater, ViewGroup container,
	            Bundle savedInstanceState) {

		    View windows = inflater.inflate(R.layout.windows_frag, container, false);
	        ((TextView)windows.findViewById(R.id.textView)).setText("Windows");
	        return windows;
}}

Finally we can proceed to MainActivity.java class .It is extended to Fragment Activity. The ViewPager Tab is set with the Adapter TabAdapter that we created earlier. We are going to enable the Tabs in the Action Bar using the statement setNavigationMode(ActionBar.NAVIGATION_MODE_TABS) . We use a TabListener in Action bar to display the Tab on selection. The Tab can be added by using addTab() method.

MainActivity.java

package com.learn2crack.tab;

import android.os.Bundle;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;

public class MainActivity extends FragmentActivity {
	ViewPager Tab;
    TabPagerAdapter TabAdapter;
	ActionBar actionBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TabAdapter = new TabPagerAdapter(getSupportFragmentManager());

        Tab = (ViewPager)findViewById(R.id.pager);
        Tab.setOnPageChangeListener(
                new ViewPager.SimpleOnPageChangeListener() {
                    @Override
                    public void onPageSelected(int position) {

                    	actionBar = getActionBar();
                    	actionBar.setSelectedNavigationItem(position);                    }
                });
        Tab.setAdapter(TabAdapter);

        actionBar = getActionBar();
        //Enable Tabs on Action Bar
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        ActionBar.TabListener tabListener = new ActionBar.TabListener(){

			@Override
			public void onTabReselected(android.app.ActionBar.Tab tab,
					FragmentTransaction ft) {
				// TODO Auto-generated method stub

			}

			@Override
			 public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {

	            Tab.setCurrentItem(tab.getPosition());
	        }

			@Override
			public void onTabUnselected(android.app.ActionBar.Tab tab,
					FragmentTransaction ft) {
				// TODO Auto-generated method stub

			}};
			//Add New Tab
			actionBar.addTab(actionBar.newTab().setText("Android").setTabListener(tabListener));
			actionBar.addTab(actionBar.newTab().setText("iOS").setTabListener(tabListener));
			actionBar.addTab(actionBar.newTab().setText("Windows").setTabListener(tabListener));

    }

}

Creating Manifest

We do not need any special permissions for our project.

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.learn2crack.tab"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="15"
        android:targetSdkVersion="19" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.learn2crack.tab.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Finally run the project in Emulator

Screenshots

android tab layout

Android Tab

android tab layout

iOS Tab

android tab layout

Windows Tab

android tab layout

Swipe from Android Tab to iOS Tab

Enjoy 🙂
Any questions comment here

Raj Amal

Raj Amal

Developer at Learn2Crack
Raj Amal is a Co-founder of Learn2Crack.com and a Android Developer. He Loves to work with Computers, Smartphones and Digital Gadgets. He also authored a book Learning Android Google Maps
Raj Amal
Tags:
  • Karthik Ramesh

    above code can you make it extends ListFragment

    • yes

      • Danny Moses

        Thanks for this. I been trying to learn android and java little by little trying to create an app. This example is awesome. I want to add a list of text to each page and change the page titles to match the contents but I’m stuck. Can you post an example of an array of text.

  • Ľuboš Mudrák

    I wonder. Is there way how to prevent constant calling of constructor of each fragments while swipping ? Only create them once and call that instance ?

  • Sylvina

    Hi, i’m working on tabsswipe project right now. But, i still don’t know how to put an expendables list view inside of my specific tab, or a button inside the tab which can go to other activity after i’ve clicked . Can you help me please?

    • It is similar to normal expendable listview, but you need to implement it in a fragment.

  • Cdn

    Hi there and thanks for this tutorial, do you know if it is possible to compile your project, so as to generate an.apk, without going through an IDE like Eclipse ?

  • Abrahim Neil

    Hey Raj nice code, much needed, please add one more functionality in existing code, to pick date and time, like this: http://www.learn2crack.com/2013/11/android-timepicker-datepicker-example.html (but this time for Fragment) and check my this issue: http://stackoverflow.com/questions/21821267/how-to-set-selected-dialog-values-to-textviews-in-fragment

  • tgrclw

    How to Theme.NoTitleBar?

    • Add this to your styles.xml file

  • Bek

    Hi Raj!
    How to start certain tab from another activity using simple button in your project? for example, to start with second tab.

  • Masha

    Heey. Great Tutorial. I have a gridview with images, when i click on one i use an adapter to pop it out onto an entire activity for viewing (like if i was to choose one). How do i swipe through the ‘popped out’ images?

  • Alex

    I need to make an activity with swipe tabs on a new window after I choose it on the menu. Can i use this code but change the names of activities and layouts?

  • Kaos1337

    There is a bug, at the launch if you log (Log.i(…)) the switch case of the tab adapter you will see that it will go from case 0 to 1 doing nothing.

  • caspecor

    how to insert this code in android tab for example?

    ////////////////////////////////////////////////////

    package com.example.multitouch;

    import java.util.ArrayList;

    import android.os.Bundle;

    import android.app.Activity;

    import android.util.Log;

    import android.view.View;

    import android.view.Window;

    import android.view.WindowManager;

    import android.widget.AdapterView;

    import android.widget.AdapterView.OnItemClickListener;

    import android.widget.ListView;

    import android.widget.Toast;

    public class CajaActivity extends Activity {

    ListView userList;

    UserCustomAdapter userAdapter;

    ArrayList userArray = new ArrayList();

    @Override

    protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    requestWindowFeature(Window.FEATURE_NO_TITLE);

    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);

    setContentView(R.layout.activity_caja);

    /*

    super.onCreate(savedInstanceState);

    requestWindowFeature(Window.FEATURE_NO_TITLE);

    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);

    setContentView(R.layout.activity_login);

    */

    /**

    * add item in arraylist

    */

    userArray.add(new Mesa(“Mesa 1”, “Total:”, “45.36 €”));

    userArray.add(new Mesa(“Mesa 2”, “Total:”, “22.68 €”));

    userArray.add(new Mesa(“Mesa 3”, “Total:”, “98.44 €”));

    userArray.add(new Mesa(“Mesa 4”, “Total:”, “12.14 €”));

    userArray.add(new Mesa(“Mesa 5”, “Total:”, “45.75 €”));

    userArray.add(new Mesa(“Mesa 6”, “Total:”, “56.85 €”));

    userArray.add(new Mesa(“Mesa 7”, “Total:”, “55.69 €”));

    /**

    * set item into adapter

    */

    userAdapter = new UserCustomAdapter(CajaActivity.this, R.layout.row,

    userArray);

    userList = (ListView) findViewById(R.id.listView);

    userList.setItemsCanFocus(false);

    userList.setAdapter(userAdapter);

    /**

    * get on item click listener

    */

    userList.setOnItemClickListener(new OnItemClickListener() {

    @Override

    public void onItemClick(AdapterView parent, View v,

    final int position, long id) {

    Log.i(“List View Clickeado”, “**********”);

    Toast.makeText(CajaActivity.this,

    “List View Clickeado:” + position, Toast.LENGTH_LONG)

    .show();

    }

    });

    }

    }

    //////////////////////////////////

  • Mohamed

    thank you.

  • Vikas

    Hi Raj
    Can you let me know how to display list of data where you are displaying Windows/IOS/Android

    • You can display list by extending the class to ListFragment.

      • Vikas

        Could you please add some example in your code.

  • Francesco

    Very helpful! Thank you very much!

  • Luis Ruiz Figueroa

    how can I choose which tab starts first?

    • Tab.setCurrentItem(int);

      Replace int with the tab number.

      • Luis Ruiz Figueroa

        pudiste hacerlo con fragment?

  • David

    Thank you, it was very helpful..

  • Hitesh

    how should i add spinners in these tab layout ?

    • For windows fragment you should add spinner like this.
      Spinner spinner =(Spinner)windows.findViewById(R.id.spinner);

      • Hitesh

        Done thanks a lot !!

  • Reinder Rae

    Thanks for your code it works really good but I have a quetion if you could help me with it, I wrote a code to call a method from tab1 to open a “fragment2” but for somereason I get a white screen, could you tell me why if you know the cause?
    this code is at MainActivity

    public void openNewsCont() {

    fragment2 nc = new fragment2();

    android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
    android.support.v4.app.FragmentTransaction ft = fm.beginTransaction();
    ft.add(R.id.pager, nc);
    ft.addToBackStack(null);
    ft.commit();

    }

    • ChaturaM

      if you want to go from tab 1 to tab two use following code

      getActivity().getActionBar().setSelectedNavigationItem(1);

  • Steve

    same coding in android hive.

    • dan

      slightly different implementation

  • Hit Chikani

    very nic example 🙂

  • dipak

    awesome it works!!, simple, easy and straightforward to follow…..now if all tutorials were like this, it would making learn so fun 🙂 thank you…

  • how to call this fragment activity from navigation slider?

  • Mounzer Orabi Agha

    Good Tutorial.. but how i can change the indicator color ( the blue color ) to custom color ? thanks you

  • How can i add more tabs

  • Maitray Shah

    How can I implement an expandable listview in one of those tabs instead of just simple text..??

  • Venkat Ramarao Potlapalli

    Hey raj… Thats a very good tutorial. But i want to add button setOnClickListener in this tabs which i’m unable to do so, can you help me out of it. Thank you in advance 🙂 🙂

  • jmz3

    Really good tutorial, helped me understand the workflow. I tried this in another way by using the ‘SectionsPagerAdapter

  • Fahad

    Great work dude

  • Guest

    Am unable to use getSupportFragmentManager()

    Error =The constructor TabPagerAdapter(FragmentManager) is undefined;

  • Syarif Ibnu Miftahudin Al-Dami

    Can i hide or remove the actionBar and just display the tabs?

  • Moises Alexander Salazar Vila

    Great tutorial! This helps me a lot !

  • Pandit

    hey Raj,
    There is problem with fragment, When I am opening first tab then second tab’s operations are performed in background but UI is of First Tab.

  • Lucas

    quality code, puts everything else to shame

  • زبیر احمد

    how set tab to bottom plz help

  • shreya

    Im really stuck at adding support libraries and updating build.gradle with dependencies for v4 libs. Do you have a tut for that? or a step by step guide. Im using Android Studio

  • Avashiva

    Hi really nice tutorial works really good, but one question how can I do for seeing my ActionBar and under it the tabs?
    I added:
    public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
    }
    But the menu tabs are on the actionbar and my menu is on overflow

    Thanks

  • Puneet

    How can I start another activity inside the same tab? e.g.from Windows.java I want to start another activity under Windows tab. Is it possible to do so? If yes, how can I do that? I am able to start another activity but it does not come within same tab but it removes the tabs layout.

  • Jaydeep Goyani

    nice work

  • Tim

    How about creating this project for API’s 11 and above ? What will be the difference ?? And how to get the ViewPager element ?

  • Linear Agressor

    You are a fuc*ing life save man !!!

  • Duy Kien Ngo

    Nice Tutorial, however what should I do if I want to put tab layout in the bottom of screen ?

  • Luba

    I keep on getting this error java.lang.RuntimeException: Unable to start activity ComponentInfo{com.azzimovrd.mobile/com.azzimovrd.mobile.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method ‘void android.app.ActionBar.setNavigationMode(int)’ on a null object reference

  • Ramal

    It looks like you are missing the TextView declaration in each of your fragments you have:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
    View android = inflater.inflate(R.layout.android_frag, container, false);
    ((TextView)android.findViewById(R.id.textView)).setText(“Android”);
    return android;
    }}

    It should say:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
    View android = inflater.inflate(R.layout.android_frag, container, false);
    TextView androidTextView = (TextView)android.findViewById(R.id.textView)).setText(“Android”);
    return android;
    }}

    ((TextView)android.findViewById(R.id.textView)).setText(“Android”); is an assignment without a declaration.

  • Vipin

    Hi
    Raj Amal,
    I wanted different tabs. And in each tab i have some text fields and button. But button click wont fire inside tab. Works fine without tab. Any idea whats wrong or could you direct me to some examples of using onclicklistener inside tab. Couldnt find one. Thanks in Advance

  • parniaznet

    how can i change tabs height?

  • Bruno Nogueira Silva

    how to send bundle to fragment

  • sky

    how to intent method for any button in android ios and widows pages.??

    • sky

      *use

  • BB

    If i place a button in windows and need to access new fragment called Blackberry by clicking it , what would be the way.

  • Wakimul Alam

    how to show this on midle of the srceen

  • Akash Lal

    Perfect Site to learn….

  • harin kaklotar

    good one, but what about Tab at bottom?

  • SENTHIL

    It shows null pointer Exception.. How can i solve that.

  • Mari Luna

    I’m looking for a more actual version without things deprecated, can anyone help me??

  • S Chaithu

    How to get settings or three dots or overflow icon in action bar?

  • Quintin Balsdon

    Thank you so much! This is way better than the shoddy Android documentation. I have been trying to do this for weeks! For people asking about how to do the custom coloring (in your styles):


    @drawable/tab_bar_background
    @null
    center

  • Chantal Bothe

    Hey, I tested the Code today and many of the

    commands are deprecated.

    For example: TabListener, setNavigarionMode, addTab…

    You have a more recent Code or know a Tutorial what shows it?
    Thanks!

  • SriRam

    HI it was really great that we had this, and really thanks for you.

    I am new to android

    I tried many of the example like this but everyone has the same bug, may be you can rectify.

    I bug is, Just go a head and write onStart and onResume functions in the frist fragment – Android fragment in this example with Log.v to be displayed.

    You observer that when you are swiping the three tabs Android>ios>windows
    and when you are returning back
    Android<IOS<Windows,
    you observe in the log cat that, when you are in IOS tab itself you can see the Logs you had written in Android Fragment.

    Due to this i am unable to move further in my project. Can you Please Help me on this.

    You can mail me on android.sidhu@gmail.com

  • Karan Khurana

    Thanks. Awesome tutorial, is there any way to disable swipe in this tutorial or swipe is active only after a certain condition is met.

  • Bernard

    nice tutorial, how can i implement listview in fragment

  • how to add listview on tab menu ? can you show me to creat one tutorials ?
    data with Mysql Thanks.

  • samir

    i want add list view with check box but problem is how i ge the checked items values in tablayout

  • Sajal Bhargava

    can u tell me what is pager (id) in this code for

  • jignesh mistry

    I get error while run this program. please give me solution

    • George

      Just change the theme in manifest and put this theme
      android:theme=”@android:style/Theme.Holo.Light.DarkActionBar”

  • Diptangsu Goswami

    firstly, thank you so much for this.
    what if i want to enter data in lets say the android activity and show it on the ios activity. how can i read data from an activity and process it?
    i am sort of working on an app which will multiply two matrices, so the first tab is for matrix 1, second one is for matrix 2 and the third one is for showing the product.
    i’d be extremely thankful if you could give me so much as a hint as to how i can solve this problem.
    thank you again.