Adding Tabs Dynamically

The TabWidget in Android is set up to allow you to easily define tabs at compile time. However, sometimes, you want to add tabs to your activity during runtime. For example, imagine an email client where individual emails get opened in their own tab, for easy toggling between messages. In this case, you don’t know how many tabs or what their contents will be until runtime, when the user chooses to open a message.

Fortunately, Android also supports adding tabs dynamically at runtime, and this blog post will show you how.

For compile-time-defined tabs, in your Java code, to set up tabs with contents provided in layout XML, you simply create a TabHost.TabSpec object and call setContent() on it, with the widget ID of the tab’s contents:

[sourcecode language=’java’]
TabHost.TabSpec spec=tabs.newTabSpec(“buttontab”);

spec.setContent(R.id.buttontab);
spec.setIndicator(“Button”);
tabs.addTab(spec);
[/sourcecode]

Adding tabs dynamically at runtime works much the same way, except you use a different flavor of setContent(), one that takes a TabHost.TabContentFactory instance. This is just a callback that will be invoked — you provide an implementation of createTabContent() and use it to build and return the View that becomes the content of the tab.

Let’s take a look at an example.

First, here is some layout XML for an activity that sets up the tabs and defines one tab, containing a single button:

[sourcecode language=’xml’]

android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
android:layout_width="fill_parent"
android:layout_height="fill_parent">
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingTop="62px">

About author

AndroidGuys
AndroidGuys 4639 posts

Founded on November 5, 2007, we've enjoyed bringing you the latest in Android news and rumors. Updated daily, we strive to deliver reviews, opinions, and updates on all things related to Android.

You might also like

News and Rumors

Which Carrier Will Rule Over the HTC Kingdom?

A second newly unearthed Android phone has been spotted online today, carrying the name of HTC Kindgom.  As with the HTC Rider, almost zero is known at this point save

News and Rumors

The Next Big Thing – Movies & Music [VIDEO]

Samsung’s latest Galaxy S II ad focuses on Android’s flexibility in download music and movies.

News and Rumors

AppBrain Breaks Down the Current State of Android Apps

The team behind AppBrain has put together a very insightful look into the Android Market and the current state of its apps.  There are some truly interesting facts to glean