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?
This example demonstrates how to use tab host in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.
In Android, TabHost is a Container for tabbed window view. This object holds two children one is set of tab labels that the user clicks to select a specific tab and other is a FrameLayout object that displays the content of that page.
TabHost consists of two children of which one is FrameLayout (which is used to show the contents of the activity) and another one is TabWidget.
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.
Finish!!!!!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With