Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
TabHost in Android with Example
Next article icon

TabHost in Android with Example

Last Updated : 25 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

TabHost is a container that holds a set of tabs. Each tab consists of either the activity or the fragments. 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.(It is used to choose the tab which the user wants to open). Mostly Tabhost is used in the project with the help of the LinearLayout. 

Important Methods of TabHost

addTab(TabSpec tabSpec): This method is used to add the new tab onto a tab widget. Whenever a new tab is being specified using TabSpec class, one needs to add that tab in our TabHost.

// initiate TabHost
TabHost tabhost = findViewById(R.id.tabhost);
// setting up the tabhost
tabhost.setup();

// setting the name of the new tab
TabHost.TabSpec spec = tabhost.newTabSpec("Tab One");

spec.setContent(R.id.tab1);
spec.setIndicator("Tab One");
// adding the tab to tabhost
tabhost.addTab(spec);

clearAllTabs(): This method is used to clear all tabs within the tab host. After adding the tab as shown above, if some want to clear the tab from TabHost, then write the below code.

tabHost.clearAllTabs(); // this method is used to clear all the tabs from tabhost

setOnTabChangedListener(OnTabChangeListener): This method is used to register a callback that needs to be invoked when the selected state of any of the items in this list changes. This method is used when one needs to invoke the callback and register it when the state changes of any selected items in the list.

setCurrentTab(int index): By default, tab hosts set the first tab position as the default position which will appear when the app is being launched, but we can explicitly change the default position of the tab using these methods. (Position starts from 0)

tabHost.setCurrentTab(1); // it will set second tab as default selected tab

Example

Let's try to understand TabHost in detail by making a small project. A sample GIF is given below to get an idea about what we are going to do in this project. We are going to implement this project using both Java and Kotlin Programming languages for Android. 


Step By Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. The code for that has been given in both Java and Kotlin Programming Language for Android.

Step 2: Working with the XML Files

Next, go to the activity_main.xml file, which represents the UI of the project. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail.

XML
<?xml version="1.0" encoding="utf-8"?><!--Linear layout as the root layout--> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     tools:context=".MainActivity">      <TabHost         android:id="@+id/tabhost"         android:layout_width="match_parent"         android:layout_height="match_parent">          <LinearLayout             android:layout_width="match_parent"             android:layout_height="match_parent"             android:orientation="vertical">              <!-- Tab widget to select the tab -->             <TabWidget                 android:id="@android:id/tabs"                 android:layout_width="match_parent"                 android:layout_height="wrap_content" />              <!-- FrameLayout which contains the data of the activity -->             <FrameLayout                 android:id="@android:id/tabcontent"                 android:layout_width="match_parent"                 android:layout_height="match_parent">                  <!-- for tab 1 -->                 <LinearLayout                     android:id="@+id/tab1"                     android:layout_width="match_parent"                     android:layout_height="match_parent"                     android:background="#FFC0CB"                     android:orientation="vertical">                      <!-- Text View for applying the text to the tab -->                     <TextView                         android:layout_width="wrap_content"                         android:layout_height="wrap_content"                         android:layout_gravity="center"                         android:layout_marginTop="270dp"                         android:text="This is Tab 1"                         android:textColor="#000"                         android:textSize="32sp" />                 </LinearLayout>                  <!-- for tab 2 -->                 <LinearLayout                     android:id="@+id/tab2"                     android:layout_width="match_parent"                     android:layout_height="match_parent"                     android:background="#90ee90"                     android:orientation="vertical">                      <!-- Text View for applying the text to the tab -->                     <TextView                         android:layout_width="wrap_content"                         android:layout_height="wrap_content"                         android:layout_gravity="center"                         android:layout_marginTop="270dp"                         android:text="This is Tab 2"                         android:textColor="#000"                         android:textSize="32sp" />                 </LinearLayout>                  <!-- for tab 3 -->                 <LinearLayout                     android:id="@+id/tab3"                     android:layout_width="match_parent"                     android:layout_height="match_parent"                     android:background="#add8e6"                     android:orientation="vertical">                      <!-- Text View for applying the text to the tab -->                     <TextView                         android:layout_width="wrap_content"                         android:layout_height="wrap_content"                         android:layout_gravity="center"                         android:layout_marginTop="270dp"                         android:text="This is Tab 3"                         android:textColor="#000"                         android:textSize="32sp" />                 </LinearLayout>             </FrameLayout>         </LinearLayout>     </TabHost> </LinearLayout> 

Step 3: Working with the MainActivity File

Go to the MainActivity File and refer to the following code. Below is the code for the MainActivity File. Comments are added inside the code to understand the code in more detail.

Java
import android.os.Bundle; import android.widget.TabHost; import androidx.appcompat.app.AppCompatActivity;  public class MainActivity extends AppCompatActivity {     @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);          // initiating the tabhost         TabHost tabhost = findViewById(R.id.tabhost);          // setting up the tab host         tabhost.setup();          // Code for adding Tab 1 to the tabhost         TabHost.TabSpec spec = tabhost.newTabSpec("Tab One");         spec.setContent(R.id.tab1);          // setting the name of the tab 1 as "Tab One"         spec.setIndicator("Tab One");          // adding the tab to tabhost         tabhost.addTab(spec);          // Code for adding Tab 2 to the tabhost         spec = tabhost.newTabSpec("Tab Two");         spec.setContent(R.id.tab2);          // setting the name of the tab 1 as "Tab Two"         spec.setIndicator("Tab Two");         tabhost.addTab(spec);          // Code for adding Tab 3 to the tabhost         spec = tabhost.newTabSpec("Tab Three");         spec.setContent(R.id.tab3);         spec.setIndicator("Tab Three");         tabhost.addTab(spec);     } } 
Kotlin
import android.os.Bundle import android.widget.TabHost import androidx.appcompat.app.AppCompatActivity  class MainActivity : AppCompatActivity() {     override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)         setContentView(R.layout.activity_main)          // initiating the tabhost         val tabhost = findViewById<TabHost>(R.id.tabhost)          // setting up the tab host         tabhost.setup()          // Code for adding Tab 1 to the tabhost         var spec = tabhost.newTabSpec("Tab One")         spec.setContent(R.id.tab1)          // setting the name of the tab 1 as "Tab One"         spec.setIndicator("Tab One")          // adding the tab to tabhost         tabhost.addTab(spec)          // Code for adding Tab 2 to the tabhost         spec = tabhost.newTabSpec("Tab Two")         spec.setContent(R.id.tab2)          // setting the name of the tab 1 as "Tab Two"         spec.setIndicator("Tab Two")         tabhost.addTab(spec)          // Code for adding Tab 3 to the tabhost         spec = tabhost.newTabSpec("Tab Three")         spec.setContent(R.id.tab3)         spec.setIndicator("Tab Three")         tabhost.addTab(spec)     } } 

Output:


Next Article
TabHost in Android with Example

L

lavishgarg26
Improve
Article Tags :
  • Java
  • Technical Scripter
  • Kotlin
  • Android
  • Technical Scripter 2020
Practice Tags :
  • Java

Similar Reads

    PhotoView in Android with Example
    In this article, PhotoView is added to android. PhotoView aims to help produce an easily usable implementation of a zooming Android ImageView using multi-touch and double-tap. Besides that, it has many more features like it notifying the application when the user taps on the photo or when the displa
    2 min read
    TextView in Android with Example
    TextView is a simple widget that is seen in every android application. This widget is used to display simple text within the android application. We can add custom styling to the text that we have to show. In this article, we will take a look at How to create a simple Text View in an android applica
    2 min read
    Android ListView in Java with Example
    A ListView in Android is a type of AdapterView that displays a vertically scrollable list of items, with each item positioned one below the other. Using an adapter, items are inserted into the list from an array or database efficiently. For displaying the items in the list method setAdaptor() is use
    3 min read
    Popup Menu in Android With Example
    In Android development, Menus are an important part of the user interface, providing users with easy access to common functionalities and ensuring a smooth and consistent experience throughout the application. In Android, we have three types of Menus available to define a set of options and actions
    4 min read
    Jetpack LiveData in Android with Example
    Android Jetpack is a suite of libraries to help developers follow best practices, reduce boilerplate code, and write code that works consistently across Android versions and devices so that developers can focus on the code they care about. Here, we are going to implement Jetpack Live Data in Android
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences