Monday, April 1, 2013

Android TabActivity | Tab Layout Demo | Tab Host Activity Example in Android

Hi Friends,

          As we know Tab-Activity is now depreciated  in Android, but some time we use it for create simple Tab pages in our application. So today I am going to share tutorial for Tab Host Activity in android. It is a simple tab activity demo, group child activity and pager tab example I will share soon. Hope my blog help you. Please follow step by step my blog for create simple Tab Layout-

Print Screen: 




1)Create a new project, name TabHostDemo.
2)Create an  TabHostActivity and extend it to TabActivity.
3)Create 3 other activity name-Homeactivity, AboutActivity, ContactActivity.
4)Create layout activity_tab_host.xml .
5)Create another 3 layout for Home, About, Contact Activity, name activity_home, activity_about, activity_contact.
6)Do optional activity for change tab images on selection.Create ic_tab_home, ic_tab_about, ic_tab_contact.
Note-this step is not must, you can direct put your images in your TabHostActivity-
// Create an Intent to launch an Activity for the tab (to be reused)
intent = new Intent().setClass(this, HomeActivity.class);
spec = tabHost.newTabSpec("home")
.setIndicator("HOME", res.getDrawable(R.drawable.home))//set here
.setContent(intent);
tabHost.addTab(spec);
7)Add images - home.png, about.png, contact.png in drawable download below images-






8)Add activity in manifest.xml
9)Run your project and enjoy :)

My Code:

1)TabHostActivity.java-
package com.manish.tabdemo;

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

public class TabHostActivity extends TabActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab_host);

Resources res = getResources(); // Resource object to get Drawables
TabHost tabHost = getTabHost(); // The activity TabHost
TabHost.TabSpec spec; // Reusable TabSpec for each tab
Intent intent; // Reusable Intent for each tab

// Create an Intent to launch an Activity for the tab (to be reused)
intent = new Intent().setClass(this, HomeActivity.class);
spec = tabHost.newTabSpec("home")
.setIndicator("HOME", res.getDrawable(R.drawable.ic_tab_home))
.setContent(intent);
tabHost.addTab(spec);

// Do the same for the other tabs

intent = new Intent().setClass(this, AboutActivity.class);
spec = tabHost.newTabSpec("about")
.setIndicator("ABOUT", res.getDrawable(R.drawable.ic_tab_about))
.setContent(intent);
tabHost.addTab(spec);


intent = new Intent().setClass(this, ContactActivity.class);
spec = tabHost
.newTabSpec("contact")
.setIndicator("CONTACT",
res.getDrawable(R.drawable.ic_tab_contact))
.setContent(intent);
tabHost.addTab(spec);

//set tab which one you want open first time 0 or 1 or 2
tabHost.setCurrentTab(0);


}

}

2)HomeActivity.java-

package com.manish.tabdemo;

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

public class HomeActivity extends Activity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
}
}

3)AboutActivity.java-

package com.manish.tabdemo;

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

public class AboutActivity extends Activity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
}
}

4)ContactActivity.java-

package com.manish.tabdemo;

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

public class ContactActivity extends Activity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact);
}
}

5)activity_tab_host.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">

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="0dip"
            android:layout_weight="1"/>

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="0"
            android:layout_marginBottom="-4dp"/>
     
    </LinearLayout>

</TabHost>

6)activity_home.xml-
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:background="#0099CC"
    android:layout_height="fill_parent" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Home Tab"
        android:textSize="35sp"
        android:textColor="#ffffff" />

</RelativeLayout>

7)activity_about.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:background="#808080"
    android:layout_height="fill_parent" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="About Tab"
        android:textSize="35sp"
        android:textColor="#ffffff" />

</RelativeLayout>

8)activity_contact.xml-
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:background="#ffdddd"
    android:layout_height="fill_parent" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Contact Tab"
        android:textSize="35sp"
        android:textColor="#000000" />

</RelativeLayout>

now put selector for tabs images in drawable folder- 

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

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

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

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.manish.tabdemo.HomeActivity"/>
             <activity android:name="com.manish.tabdemo.AboutActivity"/>
                  <activity android:name="com.manish.tabdemo.ContactActivity"/>
    </application>

</manifest>

Please feel free to post your testimonials regarding my work here. Please leave your review by clicking on comment below this post.

Thanks,

you can refer below post for child group tab-
http://www.androidhub4you.com/2013/04/android-child-group-activity-android.html

45 comments:

  1. Hi..
    I have followed all the steps as above..i added a onTabChangedListener() event to the TabHost. I am updating a TextView during tab change. but the view is not displayed. Can you help?

    ReplyDelete
    Replies
    1. Yes you should use OnResume() method for update text..
      Reason is that in case of Tab change life cycle of activity not working. I mean onCreate() method never call.
      So write your text change code inside OnResume().

      Delete
  2. I need tabbar to my all screen how is this possible

    ReplyDelete
    Replies
    1. Please try my this post-
      http://www.androidhub4you.com/2013/04/android-child-group-activity-android.html

      Delete
  3. i am getting errar in .setIndicator "not define ".so can you tell where have to define this function

    ReplyDelete
    Replies
    1. Are you copy my all code? I think something wrong in your import because no method here .setIndecatior, it is only for display text and image on your tab..see here-
      // Create an Intent to launch an Activity for the tab (to be reused)
      intent = new Intent().setClass(this, HomeActivity.class);
      spec = tabHost.newTabSpec("home")
      .setIndicator("HOME", res.getDrawable(R.drawable.ic_tab_home))
      .setContent(intent);
      tabHost.addTab(spec);

      just copy paste same as in my demo..
      and do one more thing press ctrl+shift+O
      for import missing package in your class hope it will help you..

      Delete
  4. This is very good post but you can also give the workspace of all project in a zip format and a download link.

    ReplyDelete
    Replies
    1. Thanks Kuldeep, but in case of zip code no one going to comment on my blog and for more traffic I need some comment on my post and after 100 comments I do same. I put my code on GIT, any one can download it from there, You can check my popular blogs a download link there..

      Thanks,

      Delete
  5. Thank You manish.But I dont want to display any tab to be opened when TabHostActivity is called.After clicking the tab only it has to display the respctive activity.Is it possible?
    thanks in advance.

    ReplyDelete
  6. Hi,
    I am just confused what you want? you don't want any tab? then why you are using Tabhost activity?
    And if you want open any activity on click of any tab then yes it is quiet possibile just call activity using intent instead of tabactivity-

    Intent intent=new Intent(this,HomeActivity.class)
    startActivity(intent);

    ReplyDelete
  7. i have tried your code...manish...but i dont knw what exactly happening..my code doesn't work..!

    ReplyDelete
    Replies
    1. It should work! What error you are getting?

      Delete
    2. Please download zip code from zip server-
      https://github.com/manishsri01/TabHostDemo

      Delete
  8. I want to ask. when you have 1 home screen button while pressing the button and then it moved to another Activity. TabHost bar is so or not

    ReplyDelete
    Replies
    1. Its up to you tam..
      If you call-
      Intent intent = new Intent(A.this, HomeActivity.class);
      startActivity(intent);

      it will open a page only and if you call-
      Intent intent = new Intent(A.this, TabHostActivity.class);
      startActivity(intent);

      it will open TabHost..

      Thanks,

      Delete
  9. Hi All I have put zip code on GIT server,
    please download zip code from zip server-

    https://github.com/manishsri01/TabHostDemo

    Thanks,

    ReplyDelete
  10. Can u help me on this issue
    http://stackoverflow.com/questions/17647523/how-to-create-a-lauyout-with-menu-and-autolookup-box-in-android

    ReplyDelete
  11. Okay so please put in your manifest these lines-
    supports-screens android:smallScreens="true"
    android:normalScreens="true"
    android:largeScreens="true"
    android:xlargeScreens="true"
    android:anyDensity="true"

    And put images in xxhdpi folder also..
    Hope it will help you..

    ReplyDelete
  12. Hey im getting an exception thrown when trying any kind of tab layouts. I do have a main activity screen that I do log on to before going to my next Intent please help. barant2003@gmail.com if you have the time chat thank you.

    ReplyDelete
    Replies
    1. Please download the zip code and try it should work. This is working demo...
      And for open HomeTab from after log on please call TabhostActivity in Intent.

      Delete
  13. Hey, I am implementing jfeinstein's sliding menu.. I also want to have a tab activity on the same screen but I can't extend TabActivity because my activity is already extending SlidingActivity.. How do I work around this? Need help so bad!!

    ReplyDelete
    Replies
    1. In this case I think you should not use Tab Activity, use Android Action bar.
      Search for vidio application on google play store.

      Delete
  14. Thank You manish, the tab app works fine :). but I don't get the icon showing if I have a label. the icon only shows when i remove the label.

    //this line shows me the icon
    spec = tabHost.newTabSpec("home").setIndicator("", res.getDrawable(R.drawable.ic_tab_home)).setContent(intent);

    //this line shows only label and no icon
    spec = tabHost.newTabSpec("home").setIndicator("HOME", res.getDrawable(R.drawable.ic_tab_home)).setContent(intent);

    ReplyDelete
    Replies
    1. In holo theme, the tab only support label or icon and mutually exclusive.

      After Holo, as a default the tab supposed only have label, please check the design guideline. http://developer.android.com/design/building-blocks/tabs.html

      If you willing to both label & icon at the same time, there are two options.

      Option 1: Using old Gingerbread theme. Set your android:targetSdkVersion 9 or below. (Before Honeycomb)

      Option 2: Using custom layout & view for your tab. Of course, it required some efforts, but you can use any custom layout what you want. For example:

      in your activity code:

      TabHost.TabSpec ts1;
      View tabView = getLayoutInflater().inflate(R.layout.custom_tab, tab_host, false);
      ts1 = tab_host.newTabSpec("TAB_ONE").setIndicator(tabView).setContent(R.id.edit_species_tab);

      in your layout: (whatever you want)






      Refer below URL
      http://stackoverflow.com/questions/18776694/are-label-and-icon-mutually-exclusive-in-a-tabhost-tabspec-setindicator

      Delete
  15. Hi Manish, thanks for a wonderful blog tutorial. How can move the tap layout and imagines to the top?

    ReplyDelete
    Replies
    1. sorry dear xml posting is not allow so i remove all tag please add yourself.
      Just change your activity_tab_host.xml to-

      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:layout_width="fill_parent"
      android:layout_height="fill_parent"
      android:orientation="vertical" >


      FrameLayout
      android:id="@android:id/tabcontent"
      android:layout_width="fill_parent"
      android:layout_height="0dip"
      android:layout_weight="1" >

      TabWidget
      android:id="@android:id/tabs"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:background="@color/white" />

      /FrameLayout>
      /LinearLayout>

      /TabHost>

      Delete
  16. Hi Manish, thanks for the reply, when are you going to start tutorial on Action Bar? i think its gonna be much than Tabs.

    Tx.

    ReplyDelete
    Replies
    1. Yes you are right dear. sure I will when got some spare time..
      Thanks..

      Delete
  17. Hi Manish, just one question, is it possible that we remove all taps we navigate to a new Activity? i.e we display new Activity but without taps being displayed.

    ReplyDelete
  18. Please sir i want android chat application source code please mail me sambhaji2134@gmail.com

    ReplyDelete
  19. Hello, I did everything it works but i cant see images on tabs. What is it's reason ?

    ReplyDelete
  20. hello...good tutorial... but problem is that when i switch between different tab activity is recreated...i want to resume activity if its created once

    ReplyDelete
  21. I am using sample code you have provided above but the Tabs Text is shown and the Icons Not shown.

    intent = new Intent().setClass(this, BookingsActivity.class);
    spec = tabHost.newTabSpec("bookings")
    .setIndicator("BOOKINGS", res.getDrawable(R.drawable.ic_bookings))
    .setContent(intent);//
    tabHost.addTab(spec);

    using above the Text of tabs is shown and if I change the .setIndicator("BOOKINGS", to .setIndicator( " ", then the Icon shown but text not shows, I want to show both text and its icon on Emulator AVD.

    ReplyDelete
  22. how can i change the label color of a tab when pressed??

    ReplyDelete
  23. pActivity = (AnimatedActivity)DeliveryMenuContent.this.getParent();
    Intent intent = new Intent(DeliveryMenuContent.this, DeliverySubMenuContent.class);
    i am getting an error here class cast exception cannot cast to AnimatedActivity please helpe me..........

    ReplyDelete