How do I use tabHost for Android

Steven picture Steven · Jul 24, 2012 · Viewed 48.7k times · Source

I have looked at posts on Stack Overflow and at tutorials on other websites, and I cannot understand how to use TabHost. Can someone please explain it to me and maybe send me a link to a tutorial?

Answer

jiw_cs picture jiw_cs · Jul 24, 2012

Concept TabHost

enter image description here

  1. In ManiActivity extends TabActivity

    public class MainActivity extends TabActivity {
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        //setContentView(R.layout.activity_main);
    
        TabHost mTabHost = getTabHost();
    
        mTabHost.addTab(mTabHost.newTabSpec("first").setIndicator("First").setContent(new Intent(this  ,FirstActivity.class )));
        mTabHost.addTab(mTabHost.newTabSpec("second").setIndicator("Second").setContent(new Intent(this , SecondActivity.class )));
        mTabHost.setCurrentTab(0);
    
    
    }
    }
    
  • In this activity not use layout "activity_main.xml" .

  • Tabhost mTabHost = getTabHost(); is create main tab.

  • mTabHost.newTabSpec("first") is create tabspec id "first".

  • setIndicator("First") is create text "First" in title tab.

  • setContent(new Intent(this ,FirstActivity.class )) is use content from FirstActivity.class ( FirstActivity.java )

  • mTabHost.addTab(....) is add spectab to main tab

  • mTabHost.setCurrentTab(0) is defult tab when start page.

FirstActivity.java

public class FirstActivity extends Activity{

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView( R.layout.first_layout );
}

}

SecondActivity.java

public class SecondActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView( R.layout.second_layout );
}
}
  • "R.layout.first_layout" is content from first_layout.xml

  • "R.layout.second_layout" is content from second_layout.xml

In AndroidManifest.xml add activity name ".FirstActivity" and ".SecondActivity" in example xml.

enter image description here

Finish!!!!!

enter image description here