Adding Tabs Dynamically

11

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




11 COMMENTS

  1. Is it possible to reuse same activity class for two tabs?

    I have tried to do so….OnCreate of activity called twice but onDestroy called once and crashed !!

    Any Idea weather we can use same activity class two or more time for multiple tabs in TabActivity?

    Thanks,
    jrc.src

  2. daily for 30 days that will be…

    $3000. if you make $200 daily for 30 days that will be $6000. this will only be possible if you take internet marketing as a business. do you want to promote your business over the internet? definitely there are dozens of…

  3. interview multiple candidates and get a sense…

    of what’s out there — a benchmark by which you can understand what is available, and what different writers charge for different skill levels. of course, it will be up to you to determine skill level (nobody will admit they are…

Comments are closed.