Monday, March 14, 2011

Using a TabActivity in Android

Tabs are not great in Android, but are usable in limited situations. The biggest problem with the TabActivity is trying to move to a new Activity and stay in the tab view. This was really difficult when using a WebView in a tab and the WebView content has links to additional pages. The traditional way of staying within the tabs is to have the TabActivity keep up with the current and previous Activity and switch activities when the user uses the Back button. With a WebView, this goes awray because the TabView cannot track the previous page displayed by the WebView. Since the Connexions app had this problem, I decided to exit the TabActivity after the initial Activity was used in a tab. Most apps that use tabs also do this.

Items needed to use a TabActivty
1. Create an Activity for each tab
2. Create class that extends TabActivty
3. Add entry to AndroidManifest.xml file
4. Use a layout

1. Create an Activity for each tab: Each tab will need to have an initial Activity to display when a tab is selected. My application has 3 tabs, so there are 3 activities
  • SearchActivity
  • ViewLensesActivity
  • ViewFavsActivity

2, Create class that extends TabActivty: In the onCreate() method, remove the title, ceate a TabHost and add activities for each tab to the TabHost

public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);

Resources res = getResources();
TabHost tabHost = getTabHost();
TabHost.TabSpec spec;

//add tabs to tab host
spec = tabHost.newTabSpec("search").setIndicator("Search", res.getDrawable(R.drawable.ic_tab_search)).setContent(new Intent().setClass(this, SearchActivity.class));
tabHost.addTab(spec);

spec = tabHost.newTabSpec("lenses").setIndicator("Lenses", res.getDrawable(R.drawable.ic_tab_lenses)).setContent(new Intent().setClass(this, ViewLensesActivity.class));
tabHost.addTab(spec);

spec = tabHost.newTabSpec("favs").setIndicator("Favorites", res.getDrawable(R.drawable.ic_tab_favs)).setContent(new Intent().setClass(this, ViewFavsActivity.class));
tabHost.addTab(spec);

...
}


3. Add entry to AndroidManifest.xml file: Since the TabActivity is the first Activity displayed the Connexions application, the manifest entry contains the launcher information.










4. Use a layout: The Connexions app uses main.xml as the intial layout of the app. This layout handles the .









The Tabs in the Connexions App.


As always, you can browse the source or download a zip file of the source.