TabHost in Android with Example
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 = (TabHost) findViewById(R.id.tabhost);
// setting up the tabhost
// setting the name of the new tab
TabHost.TabSpec spec = tabhost.newTabSpec(“Tab One”);
// adding the tab to tabhost
- 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 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 which of the tab using these methods. (Position starts from 0)
tabHost.setCurrentTab(1); // it will set second tab as default selected tab
Let’s try to understand the 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. Note that we are going to implement this project using the Java language.
Step by Step Implementation
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Working with the activity_main.xml file
Now go to the activity_main.xml file which represents the UI of the application. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail.
Step 3: Working with the MainActivity.kt file
Go to the MainActivity.java file, and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.