AlexVPerl AlexVPerl - 1 year ago 98
Android Question

Android TabHost Default Tab: First Added Tab Is Always Created

Consider scenario in setting initial / default tab to second tab:

TabHost _tabHost = getTabHost();
Intent intent0 = new Intent(this, Activity0.class);
Intent intent1 = new Intent(this, Activity1.class);
TabHost.TabSpec spec0 = _tabHost.newTabSpec("0").setIndicator(_vw0).setContent(intent0);
TabHost.TabSpec spec1 = _tabHost.newTabSpec("1").setIndicator(_vw1).setContent(intent1);


All resources online show that setting default tab is accomplished by calling setCurrentTab(1) - however above code will actually call Activity0's onCreate first, then Activity1's onCreate after setCurrentTab(1) line runs.

After digging around in source I noticed TabHost's addTab() method calls setCurrentTab(0) by itself first time its called:

public void addTab(TabSpec tabSpec) {

if (mCurrentTab == -1) {
setCurrentTab(0); <-- THIS will start first added Activity NO MATTER WHAT

This is obviously a problem if you want to start your app with a 2nd tab by default. I don't want to load 2 activities when I only need 1.

I was thinking of writing my own addTab method, but the implementation relies on a number of private members (most are protected but a few are private).

My Activity0 has some heavy logic on its onCreate, so I dont want to run that unnecessarily and just start on Acivity1 as default.

Any ideas ?

Answer Source

I did face the same issue and possibly the most effective solution is to create an empty invisible/hidden first tab whose activity consumes less CPU than your real one.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download