While developing your application, you may need a window that contains tabs, e.g. wizard window or settings window.
Android supports this kind of views, tabs one. Android gives you TabHost, TabWidget and TabSpec classes for building your tabbed activity.
To create your tabbed activity, you will build your layout xml file contains TabHost tag have two elements:
- TabWidget that will hold the navigation tabs title and icon
- FrameLayout that will hold LinearLayout for each tab content
Then, in your activity code you will build the tabs content, assign a title and icon for each tab and then add the tabs to your tab host object.
The following are steps for creating activity have two tabs in its view:
- Create the activity layout that contains TabHost, TabWidget and two linear layouts inside frame layout for your two tabs:
- Inside your activity onCreate method, you will init the tabs view as following:
- Acquire the tab host object and call setup() function for starting the setup
- Create your first tab by building TabSpec object and pass its layout content:
- Set the tab title and icon:
- Then, add this tab to the tab host object
- Repeat steps (2), (3) and (4) for the second tab.
tabs = (TabHost) findViewById(R.id.tabhost);
tabs.setup();TabSpec tab1 = tabs.newTabSpec("tab1");
tab1.setContent(R.id.tab1);tab1. setIndicator(“my tab one”, drawable_object);
tabs.addTab(tab1);
- Acquire the tab host object and call setup() function for starting the setup
- To set current tab, call setCurrentTab method in tab host object with the required tab index
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TabHost android:id="@+id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TabWidget
android:id="@android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="65px" />
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingTop="70px">
<LinearLayout
android:id="@+id/tab1"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</linearlayout>
<LinearLayout
android:id="@+id/tab2"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</linearlayout>
</framelayout>
</tabhost>
</linearlayout>
tabs.setCurrentTab(0);
Attached is a complete activity code and layout xml file for two tabs activity.