Android TabHost In Kotlin With Example

In this article, we will learn about android TabHost using Kotlin. We will go through various example that demonstrates how to use different attributes of TabHost. For example,

In this article, we will get answer to questions like –

  • What is TabHost?
  • Why should we consider TabHost while designing ui for any app?
  • What are possibilities using TabHost while designing ui? etc.

Let’s have a quick demo of things we want to cover in this tutorial –

Output

Tutorialwing Android TabHost Output Android TabHost in Kotlin Tutorial With Example

Tutorialwing Android TabHost Output

Getting Started

We can define android TabHost widget as below –

TabHost is a container for the tabbed window view.

TabHost contains two children. They are –

  • (a) A set of tab labels that user clicks to select a specific tab.
  • (b) A FrameLayout object that displays the selected tab views.

Now, how do we use TabHost in android application ?

Creating New Project

At first, we will create an application.
So, follow steps below to create any android project in Kotlin –

Step Description
1. Open Android Studio (Ignore if already done).
2. Go to File => New => New Project. This will open a new window. Then, under Phone and Tablet section, select Empty Activity. Then, click Next.
3. In next screen, select project name as TabHost. Then, fill other required details.
4. Then, clicking on Finish button creates new project.

Newbie in Android ?

Some very important concepts (Recommended to learn before you move ahead)

Before we move ahead, we need to setup for viewBinding to access Android TabHost Using Kotlin file without using findViewById() method.

Setup ViewBinding

Add viewBinding true in app/build.gradle file.

 
 android { 
 	// OTHER CODE... 
 	buildFeatures { 
 		viewBinding true 
 	} 
 } 
 

Now, set content in activity using view binding.
Open MainActivity.kt file and write below code in it.

 
 class MainActivity : AppCompatActivity() { 
 	
 	private lateinit var binding: ActivityMainBinding 
 	
 	override fun onCreate(savedInstanceState: Bundle?) { 
 		super.onCreate(savedInstanceState) 
 		binding = ActivityMainBinding.inflate(layoutInflater) 
 		val view = binding.root 
 		setContentView(view) 
 	} 
 } 
 

Now, we can access view in Kotlin file without using findViewById() method.

Using TabHost in Kotlin

Follow steps below to use TabHost in newly created project –

  • Open res/values/strings.xml file. Then, add below code into it.
    <resources>
        <string name="app_name">TabHost</string>
        <string name="presented_by">Presented by Tutorialwing.com</string>
        <string name="no_image">No Image</string>
        <string name="profile">Profile</string>
        <string name="recent">Recent</string>
        <string name="home">Home</string>
    </resources>
    
  • Create Pages for Each Tab in TabHost

    In this tutorial, we are going to show three tabs in the application. So, we will create three pages for tab. Their name would be as follows –

    1. HomeActivity.kt and xml file (activity_main.xml)
    2. RecentActivity.kt and xml file (activity_recent.xml)
    3. ProfileActivity.kt and xml file (activity_profile.xml)

    Create First Page(Home Page) of TabHost

    Create a new kotlin file, HomeActivity.kt, in main/java/com.tutorialwing.tabhost folder. Then, add below code into it.

    package com.tutorialwing.tabhost
    
    import android.os.Bundle
    import androidx.appcompat.app.AppCompatActivity
    import com.tutorialwing.tabhost.databinding.ActivityHomeBinding
    
    class HomeActivity : AppCompatActivity() {
    
    	private lateinit var binding: ActivityHomeBinding
    
    	override fun onCreate(savedInstanceState: Bundle?) {
    		super.onCreate(savedInstanceState)
    		binding = ActivityHomeBinding.inflate(layoutInflater)
    		val view = binding.root
    		setContentView(view)
    	}
    }
    

    Now, create xml file for this activity class in res/layout folder and name it activity_home.xml. Then, add below code into it.

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/holo_blue_dark">
    
        <TextView
            android:id="@+id/tabHeader"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="20dp"
            android:text="@string/presented_by"
            android:textColor="@android:color/white"
            android:textSize="18sp"
            android:textStyle="bold"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    
        <ImageView
            android:id="@+id/tabImage"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="20dp"
            android:contentDescription="@string/no_image"
            android:src="@mipmap/ic_launcher"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/tabHeader" />
    
        <TextView
            android:id="@+id/tabDesc"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/home"
            android:textColor="@android:color/white"
            android:textSize="17sp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/tabImage" />
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    
  • Create Second Page(Recent Page) Of TabHost

    Create a new kotlin file, RecentActivity.kt, in main/java/com.tutorialwing.tabhost folder. Then, add below code into it.

    package com.tutorialwing.tabhost
    
    import android.os.Bundle
    import androidx.appcompat.app.AppCompatActivity
    import com.tutorialwing.tabhost.databinding.ActivityRecentBinding
    
    class RecentActivity : AppCompatActivity() {
    
    	private lateinit var binding: ActivityRecentBinding
    
    	override fun onCreate(savedInstanceState: Bundle?) {
    		super.onCreate(savedInstanceState)
    		binding = ActivityRecentBinding.inflate(layoutInflater)
    		val view = binding.root
    		setContentView(view)
    	}
    
    }
    

    Now, create xml file for this activity class in res/layout folder and name it activity_recent.xml. Then, add below code into it.

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/holo_red_dark">
    
        <TextView
            android:id="@+id/tabHeader"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="20dp"
            android:text="@string/presented_by"
            android:textColor="@android:color/white"
            android:textSize="18sp"
            android:textStyle="bold"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    
        <ImageView
            android:id="@+id/tabImage"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="20dp"
            android:contentDescription="@string/no_image"
            android:src="@mipmap/ic_launcher"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/tabHeader" />
    
        <TextView
            android:id="@+id/tabDesc"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/recent"
            android:textColor="@android:color/white"
            android:textSize="17sp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/tabImage" />
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    
  • Create Third Page(Profile Page) Of TabHost

    Create a new kotlin file, ProfileActivity.kt, in main/java/com.tutorialwing.tabhost folder. Then, add below code into it.

    package com.tutorialwing.tabhost
    
    import android.os.Bundle
    import androidx.appcompat.app.AppCompatActivity
    import com.tutorialwing.tabhost.databinding.ActivityProfileBinding
    import com.tutorialwing.tabhost.databinding.ActivityRecentBinding
    
    class ProfileActivity : AppCompatActivity() {
    
    	private lateinit var binding: ActivityProfileBinding
    
    	override fun onCreate(savedInstanceState: Bundle?) {
    		super.onCreate(savedInstanceState)
    		binding = ActivityProfileBinding.inflate(layoutInflater)
    		val view = binding.root
    		setContentView(view)
    	}
    }
    

    Now, create xml file for this activity class in res/layout folder and name it activity_profile.xml. Then, add below code into it.

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/holo_green_dark">
    
        <TextView
            android:id="@+id/tabHeader"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="20dp"
            android:text="@string/presented_by"
            android:textColor="@android:color/white"
            android:textSize="18sp"
            android:textStyle="bold"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    
        <ImageView
            android:id="@+id/tabImage"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="20dp"
            android:contentDescription="@string/no_image"
            android:src="@mipmap/ic_launcher"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/tabHeader" />
    
        <TextView
            android:id="@+id/tabDesc"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/profile"
            android:textColor="@android:color/white"
            android:textSize="17sp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/tabImage" />
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    
  • Open res/layout/activity_main.xml file. Then, add below code in it –
    <?xml version="1.0" encoding="utf-8"?>
    <TabHost xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/tabHost"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">
    
            <FrameLayout
                android:id="@android:id/tabcontent"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_above="@android:id/tabs">
    
            </FrameLayout>
    
            <TabWidget
                android:id="@android:id/tabs"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true">
    
            </TabWidget>
    
        </RelativeLayout>
    
    </TabHost>
    

    In activity_main.xml file, we have defined tabHost. Inside tabHost, we have tabWidget, that shows tab labels, and frameLayout that shows views for selected tab. In our case, we will show a separate activity for each page whenever any tab is selected. Now, we will access this tabHost in kotlin file and perform some operations on it.

  • We can also access it in Kotlin File, MainActivity.kt, as below –

    package com.tutorialwing.tabhost
    
    import android.app.ActivityGroup
    import android.content.Intent
    import android.os.Bundle
    import android.widget.TabHost
    import android.widget.Toast
    import com.tutorialwing.tabhost.databinding.ActivityMainBinding
    
    class MainActivity : ActivityGroup() {
    
    	private lateinit var binding: ActivityMainBinding
    
    	override fun onCreate(savedInstanceState: Bundle?) {
    		super.onCreate(savedInstanceState)
    		binding = ActivityMainBinding.inflate(layoutInflater)
    		val view = binding.root
    		setContentView(view)
    
    		setupTabHost()
    	}
    
    	private fun setupTabHost() {
    		val tabHost = binding.tabHost
    		tabHost.setup(this.localActivityManager)
    		addTab(
    			tabHost,
    			getString(R.string.home),
    			getString(R.string.home),
    			HomeActivity::class.java
    		)
    		addTab(
    			tabHost,
    			getString(R.string.recent),
    			getString(R.string.recent),
    			RecentActivity::class.java
    		)
    		addTab(
    			tabHost,
    			getString(R.string.profile),
    			getString(R.string.profile),
    			ProfileActivity::class.java
    		)
    
    		tabHost.currentTab = 1
    		tabHost.setOnTabChangedListener { tabId ->
    			Toast.makeText(
    				applicationContext,
    				tabId,
    				Toast.LENGTH_SHORT
    			).show()
    		}
    	}
    
    	private fun addTab(tabHost: TabHost, name: String, indicator: String, className: Class<*>) {
    		val tabSpec = tabHost.newTabSpec(name)
    		tabSpec.setIndicator(indicator)
    		val intent = Intent(this, className)
    		tabSpec.setContent(intent)
    		tabHost.addTab(tabSpec)
    	}
    }
    

    We have accessed tabHost in kotlin file ( i.e. in MainActivity.kt file). Then, we have added three tab to tabHost. After that, we have defined tab change listener that displays currently selected tab.

  • Since AndroidManifest.xml file is very important in any android application, we are also going to see the content inside this file.

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.tutorialwing.tabhost">
    
        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/Theme.TabHost">
            <activity
                android:name=".MainActivity"
                android:exported="true">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
    
            <activity
                android:name=".RecentActivity"
                android:label="@string/recent" />
            <activity
                android:name=".HomeActivity"
                android:label="@string/home" />
            <activity
                android:name=".ProfileActivity"
                android:label="@string/profile" />
        </application>
    
    </manifest>
    

Now, run the application. We will get output as below –

Tutorialwing Android TabHost Output Android TabHost in Kotlin Tutorial With Example

Tutorialwing Android TabHost Output

Different Attributes of TabHost in XML

Now, we will see how to use different attributes of Android TabHost using Kotlin to customise it –

Set Id of TabHost

Many a time, we need id of View to access it in kotlin file or create ui relative to that view in xml file. So, we can set id of TabHost using android:id attribute like below –

    <TabHost
        android:id="@+id/tabHost_ID"
        />

Here, we have set id of TabHost as tabHost_ID using android:id=”” attribute. So, if we need to reference this TabHost, we need to use this id – tabHost_ID.

Set Width of TabHost

We use android:layout_width=”” attribute to set width of TabHost.
We can do it as below –

    <TabHost
        android:id="@+id/tabHost_ID"
        android:layout_width="wrap_content"
        />

Width can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value (like 20dp, 30dp etc.).

Set Height of TabHost

We use android:layout_height=”” attribute to set height of TabHost.
We can do it as below –

    <TabHost
        android:id="@+id/tabHost_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

Height can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value.

Set Padding of TabHost

We use android:padding=”” attribute to set padding of TabHost.
We can do it as below –

    <TabHost
        android:id="@+id/tabHost_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        />

Here, we have set padding of 10dp in TabHost using android:padding=”” attribute.

Set Margin of TabHost

We use android:layout_margin=”” attribute to set margin of TabHost.
We can do it as below –

    <TabHost
        android:id="@+id/tabHost_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        />

Here, we have set margin of 10dp in TabHost using android:layout_margin=”” attribute.

Set Background of TabHost

We use android:background=”” attribute to set background of TabHost.
We can do it as below –

    <TabHost
        android:id="@+id/tabHost_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#ff0000"
        />

Here, we have set background of color #ff0000 in TabHost using android:background=”” attribute.

Set Visibility of TabHost

We use android:visibility=”” attribute to set visibility of TabHost.
We can do it as below –

    <TabHost
        android:id="@+id/tabHost_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="gone"
        />

Here, we have set visibility of TabHost using android:visiblity=”” attribute. Visibility can be of three types – gone, visible and invisible

Till now, we have see how to use android TabHost using Kotlin. We have also gone through different attributes of TabHost to perform certain task. Let’s have a look at list of such attributes and it’s related task.

Different Attributes of Android TabHost Widget

Below are the various attributes that are used to customise android TabHost Widget. However, you can check the complete list of attributes of TabHost in it’s official documentation site. Here, we are going to list some of the important attributes of this widget –

Some of the popular attributes of android TabHost widget inherited from FrameLayout are –

Sr. XML Attributes Description
1 android:foregroundGravity Defines the gravity of the foreground drawable
2 android:measureAllChildren Defines whether to measure all children or only those in VISIBLE or INVISIBLE state when measuring

Some of the popular attributes of android TabHost widget inherited from ViewGroup are –

Sr. XML Attributes Description
1 android:animateLayoutChanges Defines whether LayoutTransition should run whenever there is any changes in layout
2 android:animationCache Defines whether layout animations should create a drawing cache for their children.
3 android:clipToPadding Defines whether the ViewGroup will clip its children and resize (but not clip) any EdgeEffect to its padding, if padding is not zero.
4 android:layoutAnimation Defines the layout animation to use the first time the ViewGroup is laid out.
5 android:layoutMode Defines the layout mode of this viewGroup

Some of the popular attributes of android TabHost widget inherited from View are –

Sr. XML Attributes Description
1 android:alpha Defines the alpha of the view
2 android:background Defines the background of the view
3 android:padding Defines padding of the view for all edges
4 android:tooltipText Defines text displayed in a small popup window on hover or long press
5 android:clickable Defines whether view is clickable or not
6 android:theme Defines a theme override for view
7 android:id Defines id of the view
8 android:padding Defines padding of the view

We have seen different attributes of TabHost and how to use it. If you wish to visit post to learn more about it

Thus, we have seen what is TabHost, how can we use android TabHost using Kotlin ? etc. We also went through different attributes of android TabHost.

Leave a Reply