The following is the first few sections of a chapter from The Busy Coder's Guide to Android Development, plus headings for the remaining major sections, to give you an idea about the content of the chapter.

Widget Catalog: TabHost and TabWidget

Before we had the action bar and ViewPager, we had TabHost and TabWidget as our means of displaying tabs. Nowadays, in most cases, using tabs with a ViewPager is the preferred option. However, there may be cases where the classic tabs are a better solution, or you may have inherited legacy code that still uses TabHost.

Deprecation Notes

Just as ListActivity helps one use a ListView, TabActivity helps one use a TabHost. However, TabActivity is marked as deprecated. That is largely because its parent class, ActivityGroup, is deprecated. While you can still use TabActivity, it is no longer recommended. It also is not necessary, as there are ways to use TabHost and TabWidget without using TabActivity, as will be demonstrated later in this chapter.

Key Usage Tips

There are a few widgets and containers you need to use in order to set up a tabbed portion of a view:

You load contents into that FrameLayout in one of two ways:

  1. You can define the contents simply as child widgets (or containers) of the FrameLayout in a layout XML file you are using for the whole tab setup
  2. You can define the contents at runtime

Curiously, you do not define what goes in the tabs themselves, or how they tie to the content, in the layout XML file. Instead, you must do that in Java, by creating a series of TabSpec objects (obtained via newTabSpec() on TabHost), configuring them, then adding them in sequence to the TabHost via addTab().

The two key methods on TabSpec are:

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.

A Sample Usage

The preview of this section may contain nuts.

Visual Representation

The preview of this section was the victim of a MITM ('Martian in the middle') attack.