Android TabLayout example

In this tutorial, we will demonstrates the use of TabLayout to render 4 tabs – “Android”, “Windows”, “Apple” and “BlackBerry”, each tab contains a textview to display a simple message.

P.S This project is developed in Eclipse 3.7, and tested with Android 2.3.3.

1. Tab Images

Put 4 tab images in “res/drawable” folder. The tab images used in this tutorial are not follow the Android icon guideline, sorry, i’m just not good at design :).

directory structure

2. Tab Images in XML

Create 4 XM files to tell which image to use for each tab, and put it into the same “res/drawable” folder.

File : icon_android_config.xml


<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- When selected, you should use bg with grey -->
    <item android:drawable="@drawable/ic_tab_android"
          android:state_selected="true" />
    <!-- When not selected, you should use bg with white -->
    <item android:drawable="@drawable/ic_tab_android" />
</selector>

File : icon_apple_config.xml


<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- When selected -->
    <item android:drawable="@drawable/ic_tab_apple"
          android:state_selected="true" />
    <!-- When not selected -->
    <item android:drawable="@drawable/ic_tab_apple" />
</selector>

File : icon_blackberry_config.xml


<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- When selected -->
    <item android:drawable="@drawable/ic_tab_blackberry"
          android:state_selected="true" />
    <!-- When not selected -->
    <item android:drawable="@drawable/ic_tab_blackberry" />
</selector>

File : icon_windows_config.xml


<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- When selected -->
    <item android:drawable="@drawable/ic_tab_windows"
          android:state_selected="true" />
    <!-- When not selected -->
    <item android:drawable="@drawable/ic_tab_windows" />
</selector>

3. Tab Activity

Create 4 activitiy classes, and tell which activity to use for when tab is clicked. All 4 classes are doing the same thing, display a textview component.

File : AndroidActivity.java


package com.mkyong.android;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class AndroidActivity extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        TextView textview = new TextView(this);
        textview.setText("This is Android tab");
        setContentView(textview);
    }
}

File : AppleActivity.java


package com.mkyong.android;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class AppleActivity extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        TextView textview = new TextView(this);
        textview.setText("This is Apple tab");
        setContentView(textview);
    }
}

File : BlackBerryActivity.java


package com.mkyong.android;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class BlackBerryActivity extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        TextView textview = new TextView(this);
        textview.setText("This is BlackBerry tab");
        setContentView(textview);
    }
}

File : WindowsActivity.java


package com.mkyong.android;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class WindowsActivity extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        TextView textview = new TextView(this);
        textview.setText("This is Windows mobile tab");
        setContentView(textview);
    }
}

4. Main Activity

Create an entry point, link above 4 tab activity classes with TabHost, TabSpec and etc.


package com.mkyong.android;

import android.app.TabActivity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;

public class MainActivity extends TabActivity {

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		Resources ressources = getResources(); 
		TabHost tabHost = getTabHost(); 
		
		// Android tab
		Intent intentAndroid = new Intent().setClass(this, AndroidActivity.class);
		TabSpec tabSpecAndroid = tabHost
		  .newTabSpec("Android")
		  .setIndicator("", ressources.getDrawable(R.drawable.icon_android_config))
		  .setContent(intentAndroid);

		// Apple tab
		Intent intentApple = new Intent().setClass(this, AppleActivity.class);
		TabSpec tabSpecApple = tabHost
		  .newTabSpec("Apple")
		  .setIndicator("", ressources.getDrawable(R.drawable.icon_apple_config))
		  .setContent(intentApple);
		
		// Windows tab
		Intent intentWindows = new Intent().setClass(this, WindowsActivity.class);
		TabSpec tabSpecWindows = tabHost
		  .newTabSpec("Windows")
		  .setIndicator("", ressources.getDrawable(R.drawable.icon_windows_config))
		  .setContent(intentWindows);
		
		// Blackberry tab
		Intent intentBerry = new Intent().setClass(this, BlackBerryActivity.class);
		TabSpec tabSpecBerry = tabHost
		  .newTabSpec("Berry")
		  .setIndicator("", ressources.getDrawable(R.drawable.icon_blackberry_config))
		  .setContent(intentBerry);
	
		// add all tabs 
		tabHost.addTab(tabSpecAndroid);
		tabHost.addTab(tabSpecApple);
		tabHost.addTab(tabSpecWindows);
		tabHost.addTab(tabSpecBerry);
		
		//set Windows tab as default (zero based)
		tabHost.setCurrentTab(2);
	}

}

5. Android Layout file

File : res/layout/main.xml


<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:padding="5dp">
        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:padding="5dp" />
    </LinearLayout>
</TabHost>

6. Android Manifest

At last, put everything in “AndroidManifest.xml“, defined 4 tab activity classes and set the “MainActivity” as entry point.

File : AndroidManifest.xml


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

    <uses-sdk android:minSdkVersion="10" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        
        <activity android:name=".AndroidActivity" />
        <activity android:name=".WindowsActivity" />
        <activity android:name=".AppleActivity" />
        <activity android:name=".BlackBerryActivity" />
        
        <activity
            android:label="@string/app_name"
            android:name=".MainActivity"
            android:theme="@android:style/Theme.NoTitleBar" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

7. Demo

By default, Windows tab is selected.

android tab layout example

Click on the Android tab.

android tab layout example

Download Source Code

Download it – Android-TabLayout-Example.zip (23 KB)

References

  1. Android TabLayout example
  2. Tab layout tutorial incomplete
  3. Android icon design guideline
  4. Another Android tab layout example
  5. Android TabHost Javadoc
  6. Android TabWidget Javadoc
  7. Android FrameLayout Javadoc

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
Edwin Adeola Oluwasina
Guest
Edwin Adeola Oluwasina

Thanks sir. You saved me from all night issues without a solution.

Kamal Fuad
Guest
Kamal Fuad

Is it possible to work with an activity in each of the fragment under tabs? Because i have problem to work with activity in fragment (in tabs)..

jyoti
Guest
jyoti

on tab clicking my text is not changing can u please help me

NiKhil AroRa
Guest
NiKhil AroRa

when its not working with Android Lollipop what are the alternates?
Thanks !!

Natan Rosenfeld
Guest
Natan Rosenfeld

Doesn’t work with android lollipop….

Hari
Guest
Hari

It was great thank you. keep up the Good work.

MTHD
Guest
MTHD

Awesome!

Rangga
Guest
Rangga

I’m Indonesian

Terimakasih, Semoga Amal Ibadah kamu berkah

abhishek
Guest
abhishek

not able to run application even after following all your steps

trackback
Adding xml widgets to a tab view with java | Technology & Programming

[…] I have been following this guide and i have it running. http://www.mkyong.com/android/android-tablayout-example/ […]

ahsinSidqi
Guest
ahsinSidqi

thanks a lot my friends, . . .
this is really help me,…
:D

sandeep
Guest
sandeep

Thanks buddy… Your tutorials are neat and simple..

Miki
Guest
Miki

How to make the menu vertical??

Ali
Guest
Ali

Thanks for the tutorial. Is there any open source license associated with the use of source code for TabLayout or is the sample source public domain?

Regards,
Ali

khush joshi
Guest
khush joshi

what mein of it ?xml version=”1.0″ encoding=”utf-8″?>
and this is how set in android pletform

amit
Guest
amit

can u plz show an example 4 tab layout using text as tab instead of images? or you can suggest modifications on the current example?

Vikram Viswanathan
Guest
Vikram Viswanathan

Hello,
I’m one of your fans to love your blogs on Android tutorials. In this blog I learnt about TabLayout.
In the example I’m working on, I’m using ActionBarSherlock. Since .setIndicator() is not available while extending SherlockFragmentActivity, could you please help me on this with an alternative?

I’m also trying to add icons to the tabs created.

chris
Guest
chris

For a newbie, one of the most COMPLETE and concise “how-to” on this topic I’ve found. Thanks!

sundu
Guest
sundu

hi,i m beginer of android.how to create one activity instead of another activity? pls help to make it.

trackback
Binary XML file line #4: <item> tag requires a 'duration' attribute | BlogoSfera

[…] Windows Vista x64-Bit using the eclipse IDE. After doing some thorough researching, I came across this tutorial for creating a 4 tab application. I followed the instructions closely, modifying it where […]

trackback
Binary XML file line #4: <item> tag requires a 'duration' attribute : Android Community - For Application Development

[…] Windows Vista x64-Bit using the eclipse IDE. After doing some thorough researching, I came across this tutorial for creating a 4 tab application. I followed the instructions closely, modifying it where […]

N.Nagaganesh
Guest
N.Nagaganesh

Hai,Iam a beginner in android . your apps is so good.
How do you add buttons and Other activities to each specific tab?
please tell me sir.
Thanks………………

akki
Guest
akki

hi but could u tell me how u had taken those res/drawable images how u had taken could u xpplain i’m new to android plz tell me how its possible

trackback
How to put a listview inside a tab activity? : Android Community - For Application Development

[…] Tutorial – See Here. […]

trackback
Tabs - eine kleine Frage - Android-Hilfe.de

[…] ich habe folgendes Tutorial befolgt und nun Tabs in meinem Projekt realisiert (recht klein ): Android TabLayout example Klappt auch wunderbar! Nur eine Frage: Wie kriege ich es hin, dass nicht nur ein Icon in einem […]

David
Guest
David

How do you add buttons and activities to each specific tab? For some reason it won’t work. Thanks

Vishal
Guest
Vishal

Nice tutorial
Go ahead

Stoycho Ivanov
Guest
Stoycho Ivanov

10x a lot your posts are always good for me. Ones agin 10x and keep good work…

Boris
Guest
Boris

Thx you so much !

iam fresher
Guest
iam fresher

thanks dear…