: Beginning Android

Wiring It Together

Wiring It Together

The Java code needs to tell the TabHost what views represent the tab contents and what the tab buttons should look like. This is all wrapped up in TabSpec objects. You get a TabSpec instance from the host via newTabSpec(), fill it out, then add it to the host in the proper sequence.

The two key methods on TabSpec are:

setContent(), where you indicate what goes in the tab content for this tab, typically the android:id of the view you want shown when this tab is selected

setIndicator(), where you provide the caption for the tab button and, in some flavors of this method, supply a Drawable to represent the icon for the tab

Note that tab indicators can actually be views in their own right, if you need more control than a simple label and optional icon.

Also note that you must call setup() on the TabHost before configuring any of these TabSpec objects. The call to setup() is not needed if you are using the TabActivity base class for your activity.

For example, here is the Java code to wire together the tabs from the preceding layout example:

package com.commonsware.android.fancy;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TabHost;
publicclass TabDemoextends Activity {
@Override
public voidonCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
TabHost tabs = (TabHost)findViewById(R.id.tabhost);
tabs.setup();
TabHost.TabSpec spec = tabs.newTabSpec(tag1);
spec.setContent(R.id.tab1);
spec.setIndicator(Clock);
tabs.addTab(spec);
spec = tabs.newTabSpec(tag2);
spec.setContent(R.id.tab2);
spec.setIndicator(Button);
tabs.addTab(spec);
tabs.setCurrentTab(0);
}
}

We find our TabHost via the familiar findViewById() method, then have it call setup(). After that, we get a TabSpec via newTabSpec(), supplying a tag whose purpose is unknown at this time. Given the spec, you call setContent() and setIndicator(), then call addTab() back on the TabHost to register the tab as available for use. Finally, you can choose which tab is the one to show via setCurrentTab(), providing the 0-based index of the tab.

The results can be seen in Figures 10-5 and 10-6.


Figure 10-5.The TabDemo sample application, showing the first tab


Figure 10-6.The same application, showing the second tab


: 0.479. /Cache: 3 / 1