Pages

Thursday, October 25, 2012

TabActivity example

TabActivity class is used to create Tabs in your application. You can add multiple tab in your application based on different activities of your application.

[Note: This class is deprecated from Android 3.0 Honeycomb. From Android 3.0 Fragment class is used to create Tabs.]

Though this class is deprecated you can still use because most of the Android phones run Android 2.3. Here, I have developed an application which will have five tabs for five different activities.

1. Design your screen
Let us create main activity which will have all tabs.

activity_tabed.xml 

<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>
 
TabHost is a container for a tabbed window view. This object holds two children: a set of tab labels that the user clicks to select specific tab, and a FrameLayout object that displays the content of that page. The individual element are typically controlled using this container object, rather then setting values on the child elements themselves. 

TabWidget displays a list of tab labels representing each page in the parent's tab collection. The container object for this widget is TabHost. When a user selects a tab, this object sends a message to container, TabHost, to tell to switch the display page. The container TabHost is used to add labels, add the callback handler, and manage callbacks.

Here I have developed an application having five tabs. For each tab I have created an Activity. Take a look at all five activities.
  1. AndroidActivity
  2. LinuxActivity
  3. BlackBerryActivity
  4. WindowsActivity
  5. MacActivity  

Each tab will run individual activity from above list. So, there are many files per activity, like, Java file, layout file, drawable file. Take a look at each file. Below three files belongs from only AndroidActivity. You can have same for each different tab.

activity_android.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="This is an Android Activity."
            android:textAppearance="?android:attr/textAppearanceLarge" />

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="match_parent"
            android:layout_height="300dp"
            android:src="@drawable/android" />
</LinearLayout> 

 android_cfg.xml

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

</selector>

This file highlight that which tab is selected. Each tab will have individual selector xml file. On selection of any tab the state_selected attribute will set to true so the selected tab will display in highlighted colour. All non-selected tabs will have common and other colour then the highlighted one.

AndroidActivity.java
package adnroidrises.tabedactivity;

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

public class AndroidActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_android_activoty);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_android_activoty, menu);
        return true;
    }
}  


There is nothing to code in above activity Java file. You can put your code what ever you want to put in this tab.

Like android activity you can add as many activity as many tabs you want in your application. I have added five activities to the application. 

Now lets code for main activity which will contain all five sub activities as tab. You have seen XML file for this activity. Lets have look at Java file.

package adnroidrises.tabedactivity;

import android.os.Bundle;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.TabActivity;
import android.content.Intent;
import android.content.res.Resources;
import android.view.Menu;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;

public class TabedActivity extends TabActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tabed);
        
        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.android_cfg))
                .setContent(intentAndroid);
        
        //Linux tab
        Intent intentLinux = new Intent().setClass(this, LinuxActivity.class);
        TabSpec tabSpecLinux = tabHost.newTabSpec("Linux")
                .setIndicator("Linux", ressources.getDrawable(R.drawable.linux_cfg))
                .setContent(intentLinux);    

        // Apple tab
        Intent intentApple = new Intent().setClass(this, MacActivity.class);
        TabSpec tabSpecApple = tabHost
          .newTabSpec("Apple")
          .setIndicator("", ressources.getDrawable(R.drawable.mac_cfg))
          .setContent(intentApple);

        // Windows tab
        Intent intentWindows = new Intent().setClass(this, WindowActivity.class);
        TabSpec tabSpecWindows = tabHost
          .newTabSpec("Windows")
          .setIndicator("", ressources.getDrawable(R.drawable.windows_cfg))
          .setContent(intentWindows);

        // Blackberry tab
        Intent intentBerry = new Intent().setClass(this, BlackberryActivity.class);
        TabSpec tabSpecBerry = tabHost
          .newTabSpec("Berry")
          .setIndicator("", ressources.getDrawable(R.drawable.blackberry_cfg))
          .setContent(intentBerry);

        // add all tabs 
        tabHost.addTab(tabSpecAndroid);
        tabHost.addTab(tabSpecApple);
        tabHost.addTab(tabSpecWindows);
        tabHost.addTab(tabSpecBerry);
        tabHost.addTab(tabSpecLinux);

        //set Windows tab as default (zero based)
        tabHost.setCurrentTab(0);      
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_tabed, menu);
        return true;
    }
}

As you can see I have created objects of classes Resources & TabHost. I have explained about TabHost in this article.Resources class is used for accessing an application resources. This class extends TabActivity instead of normal Activity class.

When you select any tab from application, a new activity will launch inside that tab. So, we'll need Intent to launch that activity. You'll need as many Intent objects as many tabs are there in your application.

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

In first line of above code I have created instance of Intent class which used to call AndroidActivity
Every tab has a tab indicator and a tag that is used to keep track it. 
TabSpec is used to set Indicator, Content, Label, Icon, etc. on the particular tab. I have created TabSpec object which will initialized by newTabSpec method or TabHost class, which will have tag or title as parameter. 
setIndicator will indicate TabHost that particular tab is selected or not. The file android_cfg in /res/drawable will indicate that tab is selected of not. This file will set background of tabs on the basis of that tab is selected of not. 
setContent will set the activity to launch on selection of the tab Android.

I have repeated same process for each tab I have used in my application. After creating tabs I have added all tabs to TabHost object.

tabHost.addTab(tabSpecAndroid);

addTab() method is used to add tab to TabHost object. each TabSpec object represent a  single tab. I have added all five TabSpec object to TabHost.  
Finally, you have to set any one tab as selected by default. setCurrentTab() method will set any one tab as selected by default at starting time of application. Method takes tab number starting from 0 as the parameter.

That's it, You are done with the application.

You can download file from below location.





 

9 comments:

  1. 09-20 21:54:50.759: E/AndroidRuntime(2909): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.rakeshsarangi.petrofiesta2013/com.rakeshsarangi.petrofiesta2013.MainContacts}: java.lang.IllegalArgumentException: you must specify a way to create the tab indicator.

    Getting this error

    ReplyDelete
  2. link to project does not work...

    ReplyDelete