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.
The final output of this tutorial will be like below image
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
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.
Ravi is hardcore Android programmer and Android programming has been his passion since he compiled his first hello-world program. Solving real problems of Android developers through tutorials has always been interesting part for him.
[…] http://www.androidhive.info/2011/08/android-tab-layout-tutorial/ […]
[…] Android Tab Layout Tutorial i explained how to implement a tab view. This tutorial is about implementing list view inside a tab […]
[…] 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 […]
didnt work for me.. still giving error
Thank you for this, i really appreciate.
only use in AndroidManifest.xml
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
” layout cannot be resolved or s not a field “
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?
error in main:
your content must have a ListView whose id attribute is ‘android.R.id.list’
Thanks! This is a great intro for newbies!
did not work for me, I think the instructions are incomplete.
did u try with downloaded script ?
my app crashes immediately in the simulator… how do you run the example project files in eclipse? I’m using android 2.1 sdk…
nm it works now. I dont know why it crashed before.
Great! This one works. Thank you.
Thanks!
Thanks for tutorial.. working great..
Great, Thanks!
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…
Excellent tutorial, thanks!
Is the code works perfect??
In the code “Where is the getTabHost() method”???
Hi sundar,
Check the code mentioned in 8th point.
TabHost tabHost = getTabHost();
when i runned the above code in the emulator the program gets stopped unexpectedly.can anybody help me plzzzz!!!
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
Hi ,
Thank for notifying me about the type error, but i guess SongsActivity.java and VideosActivity.java code is correct.
In all 3classes, the class declaration code are thesame “public class PhotosActivity extends Activity”
thank You very much .. article updated!
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 ..
Hi Thushara1,
The code given in article and in the download files is same.
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 ..
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.
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 ..
Wow! finally found this works for me.. thx alot 😉
U R Welcome
u r a star
U R A ROCK
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?
Hi karyne,
i think i am not using layout.xml anywhere!
What I mean is for the photos_layout.xml, songs_layout.xml and videos_layout.xml..
Karyne, Could you tell me the error you are getting?
Error:String types not allowed(at “layout_width” with value “match_parent”)
Error:String types not allowed(at “layout_height” with value “match_parent”)
Karyne ,
Check your SDK API version. It should be API Level 8.
match_parent won’t support in previous versions.
Oh thx. I am using API 7, thats y it got error.
Superb Machi ….. Its Nice and Rocking.. when compa… to Other Tutorials.. TNX……
You are welcome 🙂
source code works great! Thanks, dude!!
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.
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!
Dude…ur examples ROCK!!! dey just work……and are sooo simple to understand…………Carry on d gud work………..
Thank You..
Hello, Ravi Tamada You have done the tutorials, you can implement a ScrollHorizontal this example, but how could I do?
thank you
Hi Iomar,
Place your single tab layout inside a then you will get scroll bar.
this example don’t work for me. the applicacion crashes, help ?
log cat: fatal example main
unable to start activity
Could you give me complete log error report ?
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.
try to add one more TabSpec
Nice tutorial
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
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.
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.
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!
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
This tabhost example and Json parsing example are very useful to me. Thanks.
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!
You can done using xml or through color
http://stackoverflow.com/questions/4127446/custom-style-for-androids-tabwidget
http://stackoverflow.com/questions/3903796/custom-tabs-in-android
thanks a lot…i’m being a hassle i apologise
!
No problem at all 🙂
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!”
Hi Binhloan,
It would be helpful if you give me your error log cat report.
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
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.
Eclipse version 3.7.1 versión classic? better use Eclipse IDE for Java EE Developers
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!
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.
Thank u so much… am so happy for this codeing
Thanx alot. It really worked. Keep up the great work
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!!
Hey, Its not working… actually does’nt show error but still display FORCE CLOSE in emmulator
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
Try to replace match_parent with fill_parent.
THAAAAAANK YOU!!!!!
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
Hi Shishir,
Thanks for the great idea. I’ll think about this.
Eres un crack, gracias carnal!!!
Dice el alexander que si de una vez le programas la interfaz de cartelera, que porque el no puede!!!…………. n_n
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.
That will be next post 🙂
how can i change the text size and color of tabs
not work
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?
I also get this error on the manifesto
‘Error: No resource found that matches the given name (at ‘icon’ with value ‘@drawable/icon’).’
Make sure that you have a image file called “icon” in drawable folder.
(hdpi, mdpi, ldpi – in any folder)
Delete R file and build project again. It will generate a new file.
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
hi ,im trying the sama code but it doesn’t work.please help me!
The error “The application … has stopped.!”
check you log cat for errors.