1

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);
_tabHost.addTab(tabSpec0);
_tabHost.addTab(tabSpec1);

_tabHost.setCurrentTab(1);

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 ?

AlexVPerl
  • 7,652
  • 8
  • 51
  • 83
  • maybe you don't need to set the "setContent(intent)" method until the user press the tab, then you check if exist the content to "setContent(intent) or not. Anyway i use always fragments for tabs not activities. Why need to start on tab 2? swapping the tab order fix this and from your short info seems a better approach. – Sulfkain Jun 10 '15 at 10:04
  • Thanks, I feel that would work. Can you provide a quick code sample? – AlexVPerl Jun 10 '15 at 19:06
  • If you can change the order of the tab, that doesn't need any code, i prefer this approach so far. – Sulfkain Jun 11 '15 at 07:06
  • Thanks but I can't change the tab order based on design specs. I like the idea of changing the view Content you mentioned. That would work, but I can't seem to find the API for modifying the content of views after the tab is added. – AlexVPerl Jun 11 '15 at 07:08
  • Ok, i will take a look at doc, i don't remember exactly how to do, i will tell you something later. – Sulfkain Jun 11 '15 at 08:59

1 Answers1

1

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.

Community
  • 1
  • 1
Grzegorz Adam Hankiewicz
  • 7,349
  • 1
  • 36
  • 78
  • this is a great suggestion which gave me another idea. I can also set a global flag upon first load to bypass act load logic. Thanks – AlexVPerl Nov 24 '16 at 14:20