As tabhost is deprecated by android it is not recommended to implement tab layout using the way mentioned in this article. Consider reading updated article about implementing tab layout using Fragments and ViewPager Android Tab Layout with Swipeable Views

In my previous article Android Layouts i explained about three layouts (Linear Layout, Relative Layout and Table Layout). In this post i will be discussing about Android Tab Layout. This is a simple tab layout contains 3 tabs.

Download Code

The final output of this tutorial will be like below image

Android Tab Layout output

In this post we need three separate activities for three tab screens. So let’s get started by creating a simple project by opening eclipse IDE.

1. Create a new project File -> New -> Android Project and give activity name as AndroidTabLayoutActivity.
2. Open your AndroidTabLayoutActivity and extend the class from TabActivity.

public class AndroidTabLayoutActivity extends TabActivity {

3. Now open your main.xml under res -> layout folder and type the following code.

<?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">
        <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"/>
    </LinearLayout>
</TabHost>

4. Now we need 3 activities and 3 xml layouts for three tabs. So create three activities by right click on your package folder and create classes and name them as PhotosActivity.java, SongsActivity.java and VideosActivity.java. Type the following code respectively.
Right Click on package folder -> New -> Class

package com.example.androidtablayout;

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

public class PhotosActivity extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.photos_layout);
    }
}
package com.example.androidtablayout;

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

public class SongsActivity extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.songs_layout);
    }
}
package com.example.androidtablayout;

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

public class VideosActivity extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.videos_layout);
    }
}

5. Now create 3 xml layouts by right clicking on res/layout -> New -> Android XML File and name them as photos_layout.xml, songs_layout.xml and videos_layout.xml and type the following code in respective files.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
  
  <!-- Screen Design for Photos -->
  <TextView android:text="PHOTOS HERE"
  			android:padding="15dip"
  			android:textSize="18dip"
  			android:layout_width="fill_parent"
  			android:layout_height="wrap_content"/>
    
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
  
  <!-- Screen Design for the SONGS -->
  <TextView android:text="SONGS HERE"
  			android:padding="15dip"
  			android:textSize="18dip"
  			android:layout_width="fill_parent"
  			android:layout_height="wrap_content"/>
</LinearLayout>

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
  
  <!--  Screen Design for VIDEOS -->
  <TextView android:text="VIDEOS HERE"
  			android:padding="15dip"
  			android:textSize="18dip"
  			android:layout_width="fill_parent"
  			android:layout_height="wrap_content"/>
</LinearLayout>

6. Each and every tab needs an icon so design icons for each tab. We need three dimensions of each icon. Design each icon in 48 x 48 px, 32 x 32 px and 24 x 24 px and place them in drawable-hdpi, drawable-mdpi and drawable-ldpi respectively. See following diagram for your guidance

Android icon sizes

7. Android icon states will be define in xml files with default and hover state configurations. For three icons we need the icon state configuration files. So create three 3 xml files under drawable-hdpi directory. Type the following code for icon states.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- When selected, use grey -->
    <item android:drawable="@drawable/photos_gray"
          android:state_selected="true" />
    <!-- When not selected, use white-->
    <item android:drawable="@drawable/photos_white" />
</selector>
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- When selected, use grey -->
    <item android:drawable="@drawable/songs_gray"
          android:state_selected="true" />
    <!-- When not selected, use white-->
    <item android:drawable="@drawable/songs_white" />
</selector>
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- When selected, use grey -->
    <item android:drawable="@drawable/videos_gray"
          android:state_selected="true" />
    <!-- When not selected, use white-->
    <item android:drawable="@drawable/videos_white" />
</selector>

8. Now open AndroidTabLayoutActivity.java and type the following code. In the following code we are creating three TabSepcs and adding them to TabHost.

package com.example.androidtablayout;

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

public class AndroidTabLayoutActivity extends TabActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        TabHost tabHost = getTabHost();
        
        // Tab for Photos
        TabSpec photospec = tabHost.newTabSpec("Photos");
        // setting Title and Icon for the Tab
        photospec.setIndicator("Photos", getResources().getDrawable(R.drawable.icon_photos_tab));
        Intent photosIntent = new Intent(this, PhotosActivity.class);
        photospec.setContent(photosIntent);
        
        // Tab for Songs
        TabSpec songspec = tabHost.newTabSpec("Songs");        
        songspec.setIndicator("Songs", getResources().getDrawable(R.drawable.icon_songs_tab));
        Intent songsIntent = new Intent(this, SongsActivity.class);
        songspec.setContent(songsIntent);
        
        // Tab for Videos
        TabSpec videospec = tabHost.newTabSpec("Videos");
        videospec.setIndicator("Videos", getResources().getDrawable(R.drawable.icon_videos_tab));
        Intent videosIntent = new Intent(this, VideosActivity.class);
        videospec.setContent(videosIntent);
        
        // Adding all TabSpec to TabHost
        tabHost.addTab(photospec); // Adding photos tab
        tabHost.addTab(songspec); // Adding songs tab
        tabHost.addTab(videospec); // Adding videos tab
    }
}

9. Now everything is ready and before running your project make sure that you an entry of new activity name in AndroidManifest.xml file. Open you AndroidManifest.xml file and modify the code as below

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

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".AndroidTabLayoutActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
        <!--  Songs Activity -->
        <activity android:name=".SongsActivity" />
        
        <!--  Videos Activity -->
        <activity android:name=".VideosActivity" />
        
        <!--  Photos Activity -->
        <activity android:name=".PhotosActivity" />

    </application>
</manifest>

10. Finally run your project by right clicking on your project folder -> Run As -> 1 Android Application. You will see simple tabs app with awesome navigation.

Subscribe
Notify of
guest
295 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
trackback

[…] Android Tab Layout Tutorial i explained how to implement a tab view. This tutorial is about implementing list view inside a tab […]

trackback

[…] tạo giao diện như hình dưới. Cảm ơn Cái này là tab. Link tutorial tham khảo : link Trả lời với trích dẫn […]

Pavneet
Pavneet
7 years ago

didnt work for me.. still giving error

Amukelani
Amukelani
7 years ago

Thank you for this, i really appreciate.

Van Tai Le
Van Tai Le
7 years ago

only use in AndroidManifest.xml

RickM
RickM
7 years ago

It doesn’t run! Always the same problem, those classes .java has an error on R.layout and I dont know why! The code is the same but its not working

RickM
RickM
7 years ago
Reply to  RickM

” layout cannot be resolved or s not a field “

Victor
Victor
7 years ago

Thanks for your tutorial, its working fine but i’m having a problem, i imported content for a tab, when i run it separately everything is working fine but when its under a tab, my spinners are blank and my buttons arent working as they should, toasters not apearing on screen, what can the problem be?

Satnam
Satnam
7 years ago

error in main:
your content must have a ListView whose id attribute is ‘android.R.id.list’

Kevin
Kevin
9 years ago

Thanks! This is a great intro for newbies!

Christopher
Christopher
9 years ago
Reply to  Kevin

did not work for me, I think the instructions are incomplete.

Ravi Tamada
9 years ago
Reply to  Christopher

did u try with downloaded script ?

Gee
Gee
9 years ago
Reply to  Christopher

my app crashes immediately in the simulator… how do you run the example project files in eclipse? I’m using android 2.1 sdk…

Gee
Gee
9 years ago
Reply to  Gee

nm it works now. I dont know why it crashed before.

ug
ug
9 years ago

Great! This one works. Thank you.

Nguyen van trong
Nguyen van trong
9 years ago

Thanks!

venkatesh
venkatesh
9 years ago

Thanks for tutorial.. working great..

suo bao
suo bao
9 years ago

Great, Thanks!

guest132
guest132
9 years ago

I am using the Android 3.1 (Tablet) and the result is only 1/3 of the screen.
Could anyone help me, so it could show on full screen?
Thx…

rb
rb
9 years ago

Excellent tutorial, thanks!

sundar
sundar
9 years ago

Is the code works perfect??

sundar
sundar
9 years ago

In the code “Where is the getTabHost() method”???

Ravi Tamada
9 years ago
Reply to  sundar

Hi sundar,

Check the code mentioned in 8th point.
TabHost tabHost = getTabHost();

sundar
sundar
8 years ago

when i runned the above code in the emulator the program gets stopped unexpectedly.can anybody help me plzzzz!!!

guest132
guest132
8 years ago
Reply to  sundar

There is a typo in no.4, “VidesActivity.java” instead of “VideosActivity.java” and also the SongsActivity.java and VideosActivity.java codes show the code of PhotosActivity.java

Ravi Tamada
8 years ago
Reply to  guest132

Hi ,

Thank for notifying me about the type error, but i guess SongsActivity.java and VideosActivity.java code is correct.

guest132
guest132
8 years ago
Reply to  Ravi Tamada

In all 3classes, the class declaration code are thesame “public class PhotosActivity extends Activity”

Ravi Tamada
8 years ago
Reply to  guest132

thank You very much .. article updated!

Thushara1
Thushara1
8 years ago

Sample works , but code describe here is not working . actually i want tab with icons and call different activity for each tab .. this sample code is meet my requirement .unfortunately this is not working for me .. sample code give to down load is working but there is not that features .. appreciate if can make this sample works ..

Ravi Tamada
8 years ago
Reply to  Thushara1

Hi Thushara1,

The code given in article and in the download files is same.

Thushara1
Thushara1
8 years ago
Reply to  Ravi Tamada

Wonder , when i run the sample from code downloaded from site , its gives tab with out icons also its display just a test when select tab .. those are not coming from different activities .the way do the code is different . i have refer similar sample given android doc ..but there also getting same error .. pls any clue on this ..

Ravi Tamada
8 years ago
Reply to  Thushara1

Try to close your eclipse IDE and open again. In your Android Emulator uninstall your tab application and run the project again.
Still if you have problem you can send me your source code files i may help you.

Thushara1
Thushara1
8 years ago
Reply to  Ravi Tamada

Thanks a lot for your prompt response .. its done .. i have made small mistake . my AVD was 2.1 and i have create 2.2 one run . its works .. also earlier i have refer some other code accidently . code is same .Thanks a lot again ..
all the samples are great and very helpful ..

Karyne
Karyne
8 years ago

Wow! finally found this works for me.. thx alot 😉

Ravi Tamada
8 years ago
Reply to  Karyne

U R Welcome

Naila_anjum
Naila_anjum
8 years ago
Reply to  Ravi Tamada

u r a star

Login
Login
8 years ago
Reply to  Naila_anjum

U R A ROCK

Chin
Chin
8 years ago

Hi. I had copied everything from this page but I have problem with the “match_parent” in those layout.xml file. What might be the reason for it?

Ravi Tamada
8 years ago
Reply to  Chin

Hi karyne,

i think i am not using layout.xml anywhere!

Chin
Chin
8 years ago
Reply to  Ravi Tamada

What I mean is for the photos_layout.xml, songs_layout.xml and videos_layout.xml..

Ravi Tamada
8 years ago
Reply to  Chin

Karyne, Could you tell me the error you are getting?

Chin
Chin
8 years ago
Reply to  Ravi Tamada

Error:String types not allowed(at “layout_width” with value “match_parent”)
Error:String types not allowed(at “layout_height” with value “match_parent”)

Ravi Tamada
8 years ago
Reply to  Chin

Karyne ,

Check your SDK API version. It should be API Level 8.

match_parent won’t support in previous versions.

Chin
Chin
8 years ago
Reply to  Ravi Tamada

Oh thx. I am using API 7, thats y it got error.

Raviindianstar
Raviindianstar
8 years ago
Reply to  Chin

Superb Machi ….. Its Nice and Rocking.. when compa… to Other Tutorials.. TNX……

Ravi Tamada
8 years ago
Reply to  Raviindianstar

You are welcome 🙂

William
William
8 years ago

source code works great! Thanks, dude!!

PassingThru
PassingThru
8 years ago

Thanks. This helped perfectly. I just needed the tip on what to pass in in order to format the layout using XML instead of Java. You had wanted was needed.

Phil
8 years ago

Great example, followed it to the letter and now have a working tab framework. Been struggling for over an hour with the google documentation before I found this page. Wish I’d found this first!

Nitin Bansal
Nitin Bansal
8 years ago

Dude…ur examples ROCK!!! dey just work……and are sooo simple to understand…………Carry on d gud work………..

Ravi Tamada
8 years ago
Reply to  Nitin Bansal

Thank You..

Iomar Santos
Iomar Santos
8 years ago

Hello, Ravi Tamada You have done the tutorials, you can implement a ScrollHorizontal this example, but how could I do?

thank you

Ravi Tamada
8 years ago
Reply to  Iomar Santos

Hi Iomar,

Place your single tab layout inside a then you will get scroll bar.

Reciclagem
Reciclagem
8 years ago

this example don’t work for me. the applicacion crashes, help ?

log cat: fatal example main
unable to start activity

Ravi Tamada
8 years ago
Reply to  Reciclagem

Could you give me complete log error report ?

Kamleshgaonkar
Kamleshgaonkar
8 years ago

I want to add more tabs in this so can we do this with horizontal scroll view like android music or android new market style. Please help.

Ravi Tamada
8 years ago
Reply to  Kamleshgaonkar

try to add one more TabSpec

a.Khan
a.Khan
8 years ago

Nice tutorial

Roco Escalera Tapias
Roco Escalera Tapias
8 years ago

Hi Ravi,

I don’t get the icons on the tabs. Even if I try to set the default icon from the app which DOES show up on to the topbar, this won’t show on the tabs.

Also, the “Photos, Songs and Videos” Strings only show up in capital letters. ¿?

I’m on API 15

Ravi Tamada
8 years ago

Hi Roco,

Once try to run downloaded script (given in this tutorial) and check whether everything is working or not. If it does we can find out the problem in your project.

Robbie
Robbie
8 years ago

Hi Roco, Did you find a solution/the cause of this problem I am having the same issues where the images will not show and text is all in capitals.

davey
davey
8 years ago

Thank You so much for making this great, simple and straightforward tabs tutorial. It’s perfect!!

Just a little question: It’s surprising that icons_photo_tab.xml, icon_songs_tab.xml & icon_videos_tab.xml files all go into the drawable-hdpi directory instead of the layout directory.

Any chance you can explain why this is the case? Thanks so much, and thanks again for making such a clear tutorial!

Ravi Tamada
8 years ago
Reply to  davey

Hi Davey,

Good question. Although these 3 are xml files, they are not layout files instead they dealt with icon states. So these files placed in drawble folder. It is compulsory to place icon files in drawable folder otherwise you can’t access via R.drawable.icon

Thank You

Praveen Kumar
Praveen Kumar
8 years ago

This tabhost example and Json parsing example are very useful to me. Thanks.

Fadi Ramadan
Fadi Ramadan
8 years ago

Hello Ravi
I have a question are you able to change the colors?
change the orange (when selected) to something else?
thanks alot for all ur help!

Fadi Ramadan
Fadi Ramadan
8 years ago
Reply to  Ravi Tamada

thanks a lot…i’m being a hassle i apologise
!

Ravi Tamada
8 years ago
Reply to  Fadi Ramadan

No problem at all 🙂

Binhloan
Binhloan
8 years ago

In spite of, I had written exactly what you have shown, but it doesn’t work. Please help me.
The error “The application … has stopped. Please try again!”

Ravi Tamada
8 years ago
Reply to  Binhloan

Hi Binhloan,

It would be helpful if you give me your error log cat report.

Kevin Meta Agostini
8 years ago

Hey

I did all this but i got 3 errors:
photospec.setIndicator(“Photos”, getResources().getDrawable(R.drawable.icon_photos_tab));

R Cammpt be resolved as a variable… you got a work around for this?

Thanks

Ravi Tamada
8 years ago

Hi Kevin,

make sure that you have all icons and related xml files in drawble folder. If you are sure about that, delete your R.java file under gen folder and build your project again( or it will build automatically).

I hope this solves your issue.

Luis Cifuentes
Luis Cifuentes
8 years ago

Eclipse version 3.7.1 versión classic? better use Eclipse IDE for Java EE Developers

Kaiser
Kaiser
8 years ago

I don’t really know how to explain this. I loaded this project in Eclipse, ran it and it worked nicely on my cell. Next, I made a small text change, modifed “PHOTOS HERE” to “PHOTOS THERE”. The project doesn’t run any more! I get the error “C:AndroidWorkworkspaceAndroidTabLayoutAndroidTabLayoutreslayoutphotos_layout.out.xml:1: error: Error parsing XML: no element found”

What is going on? I copy the project files again afresh and it start working only to stop with another minor change. Help please!

Ravi Tamada
8 years ago
Reply to  Kaiser

Hi Kaiser,

It may be problem with building your project. Goto Project -> un check Build Automatically. And each time your modify something right click on your project and build project.

Ronald Antony
Ronald Antony
8 years ago

Thank u so much… am so happy for this codeing

Kate chuagah
Kate chuagah
8 years ago

Thanx alot. It really worked. Keep up the great work

benny
benny
8 years ago

Hi there, this layout looks awesome. I’ve got a question though. As my main.xml is used as a login page, I tried loading this tab on my 2nd page but it does not seem to be working. Any ideas? Help please!!

Abha
Abha
8 years ago
Reply to  benny

Hey, Its not working… actually does’nt show error but still display FORCE CLOSE in emmulator

Kmarine0120
Kmarine0120
8 years ago

The problem I have is the XML files for each of the layouts (ie. songs_layout etc.) are giving me errors. Here is the code.

It is saying match parent is not allowed and it is also saying that the text is a warning here are the errors.

error: Error: String types not allowed (at ‘layout_width’ with value ‘match_parent’).

and

[I18N] Hardcoded string “Movies”, should use @string resource

Ravi Tamada
8 years ago
Reply to  Kmarine0120

Try to replace match_parent with fill_parent.

Aida
Aida
8 years ago

THAAAAAANK YOU!!!!!

Shishir
Shishir
8 years ago

Hi..Nice tutorial..
how can i scroll the tab horizontally…like if initially its in ‘photo tab’ and if i scroll horizontally then ‘songs tab’ should show up and then video tab..
can u plz help me!

thanks

Ravi Tamada
8 years ago
Reply to  Shishir

Hi Shishir,

Thanks for the great idea. I’ll think about this.

Algo
Algo
8 years ago

Eres un crack, gracias carnal!!!

Algo
Algo
8 years ago
Reply to  Algo

Dice el alexander que si de una vez le programas la interfaz de cartelera, que porque el no puede!!!…………. n_n

Nagraj S.M
Nagraj S.M
8 years ago

Thank u bro. But i’ve one doubt, in my app i’m trying to add two tabs in each parent tab. I mean in your example, the PHOTOS tab should contain 2 more tabs below the text you displayed and the same for rest of the two parent tabs.
Could you please post this example.

Ravi Tamada
8 years ago
Reply to  Nagraj S.M

That will be next post 🙂

Mo3taz90
Mo3taz90
8 years ago

how can i change the text size and color of tabs

Regcosta
Regcosta
8 years ago

not work

0m3g4
0m3g4
8 years ago

Followed the tutorial step by step and can’t find where I made a mistake, I keep getting “R cannot be resolved to a variable” in every single spot ‘R’ appears such as:

setContentView(R.layout.main);

Also, this didn’t happen before I finally updated the Manifesto at the end, but instead of not finding R, the compilator couldn’t find the directory after the ‘R’. Hope I make it understandable enough, any thoughts?

0m3g4
0m3g4
8 years ago
Reply to  0m3g4

I also get this error on the manifesto
‘Error: No resource found that matches the given name (at ‘icon’ with value ‘@drawable/icon’).’

Ravi Tamada
8 years ago
Reply to  0m3g4

Make sure that you have a image file called “icon” in drawable folder.
(hdpi, mdpi, ldpi – in any folder)

Ravi Tamada
8 years ago
Reply to  0m3g4

Delete R file and build project again. It will generate a new file.

Harish R
8 years ago

Hi Ravi
i have a query need to create a tab based application i ve put ma query here can u please go through it and suggest me the possibilities

http://www.anddev.org/other-coding-problems-f5/tab-layout-with-next-previous-button-for-tab-navigation-t1148825.html

Raouabenfredj
Raouabenfredj
8 years ago

hi ,im trying the sama code but it doesn’t work.please help me!
The error “The application … has stopped.!”

Ravi Tamada
8 years ago
Reply to  Raouabenfredj

check you log cat for errors.

295
0
Would love your thoughts, please comment.x
()
x