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”);


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’]


About author

AndroidGuys 4625 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

Alleged Galaxy S5 specs found on benchmark site

One of the expected Galaxy S5 variants, the SM-G900F, has once again shown up in a benchmark, this time on AnTuTu’s benchmark database. The AnTuTu team says it’s “almost sure” this is the international

News and Rumors

RunKeeper Pro is FREE Through The Month of January!

RunKeeper is a great weight tracking tool that lets you use your mobile phone and the website to keep track of your fitness. There is a free standard app, and now, the PRO app is FREE for the month of January. (Sources say that you can pick it up a day or two early for free, also.)

News and Rumors

Three out of Four Android Phones at 2.1 or Higher

Google’s latest platform version data is out, collected from the Android Market during the two weeks leading to November 1.  Most telling in the report is that 77-percent of Android