Android Toolbar Using Kotlin With Example

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

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

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

Getting Started

We can define android Toolbar widget as below –

Toolbar is generalized version of action bar. It can be placed at any place in view hierarchy.

Now, how do we use Toolbar 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 Toolbar. 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 Toolbar 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 Toolbar in Kotlin

Follow steps below to use Toolbar in newly created project –

  • Open res/values/strings.xml file. Then, add below code into it.
    <resources>
        <string name="app_name">Toolbar</string>
    </resources>
    
  • Open res/layout/activity_main.xml file. Then, add below code in 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"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    
            <androidx.appcompat.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:background="?attr/colorPrimary"
                android:minHeight="?attr/actionBarSize"
                android:theme="?attr/actionBarTheme"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    
  • We can also access it in Kotlin File, MainActivity.kt, as below –

    package com.tutorialwing.toolbar
    
    import androidx.appcompat.app.AppCompatActivity
    import android.os.Bundle
    import com.tutorialwing.toolbar.databinding.ActivityMainBinding
    
    class MainActivity : AppCompatActivity() {
    
    	private lateinit var binding: ActivityMainBinding
    
    	override fun onCreate(savedInstanceState: Bundle?) {
    		super.onCreate(savedInstanceState)
    
    		binding = ActivityMainBinding.inflate(layoutInflater)
    		setContentView(binding.root)
    
    		setSupportActionBar(binding.toolbar)
    	}
    }
    

Now, run the application. We will get output as below –
Tutorialwing Kotlin Android Toolbar Using Kotlin With Example

Set Title in Toolbar

We can set title using app:title=”” attribute as below –

<androidx.appcompat.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    android:minHeight="?attr/actionBarSize"
    android:theme="?attr/actionBarTheme"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:title="Android ToolBar"/>

Run app, we will get output as below –
Tutorialwing Kotlin Android Toolbar Using Kotlin With Example

Set SubTitle in Toolbar

We can set sub title using app:subtitle=”” as below –

<androidx.appcompat.widget.Toolbar
   android:id="@+id/toolbar"
   android:layout_width="0dp"
   android:layout_height="wrap_content"
   android:background="?attr/colorPrimary"
   android:minHeight="?attr/actionBarSize"
   android:theme="?attr/actionBarTheme"
   app:layout_constraintEnd_toEndOf="parent"
   app:layout_constraintStart_toStartOf="parent"
   app:layout_constraintTop_toTopOf="parent"
   app:subtitle="Subtitle"
   app:title="Android ToolBar" />

Run app, we will get output as below –
Tutorialwing Set Sub Title in Toolbar in Kotlin

Set Logo in Toolbar

We can set logo in toolBar using app:logo=”” as below –

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:background="?attr/colorPrimary"
            android:minHeight="?attr/actionBarSize"
            android:theme="?attr/actionBarTheme"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:title="Android ToolBar"
            app:subtitle="Subtitle"
            app:logo="@drawable/ic_person" />

Run app, we will get output as below –
Tutorialwing Kotlin Android Toolbar Using Kotlin With Example

Set Navigation Icon in Toolbar

We can set navigation icon in toolbar using app:navigationIcon=”” as below –

            <androidx.appcompat.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:background="?attr/colorPrimary"
                android:minHeight="?attr/actionBarSize"
                android:theme="?attr/actionBarTheme"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                app:logo="@drawable/ic_person"
                app:navigationIcon="@drawable/ic_menu"
                app:subtitle="Subtitle"
                app:title="Android ToolBar" />

Here, we have set ic_menu icon from drawable folder as navigation icon in toolbar.
Run app, we will get output as below –
Tutorialwing Kotlin Android Toolbar Using Kotlin With Example set Navigation icon

Set Custom Theme in Toolbar

Follow steps below to set custom theme in toolbar –

  1. Open themes.xml file present inside res/values folder. Then, add below code in it –
        <!-- Custom theme of toolBar -->
        <style name="CustomToolBarStyle" parent="Widget.AppCompat.Toolbar">
            <item name="android:background">#FFC0CB</item>
            <item name="titleTextAppearance">@style/CustomTitleTextAppearance</item>
            <item name="subtitleTextAppearance">@style/CustomSubTitleTextAppearance</item>
        </style>
    
        <style name="CustomTitleTextAppearance" parent="TextAppearance.Widget.AppCompat.Toolbar.Title">
            <item name="android:textSize">18sp</item>
            <item name="android:textColor">#ff00ff</item>
        </style>
    
        <style name="CustomSubTitleTextAppearance" parent="TextAppearance.Widget.AppCompat.Toolbar.Subtitle">
            <item name="android:textSize">14sp</item>
            <item name="android:textColor">#808080</item>
        </style>
    
  2. Then, add @style/CustomToolBarStyle line in application’s base theme inside themes.xml file.

    Finally, code inside themes.xml file is –

    <resources xmlns:tools="http://schemas.android.com/tools">
    
        <!-- Base application theme. -->
        <style name="Theme.Toolbar" parent="Theme.MaterialComponents.DayNight.NoActionBar">
            <!-- Primary brand color. -->
            <item name="colorPrimary">@color/purple_500</item>
            <item name="colorPrimaryVariant">@color/purple_700</item>
            <item name="colorOnPrimary">@color/white</item>
            <!-- Secondary brand color. -->
            <item name="colorSecondary">@color/teal_200</item>
            <item name="colorSecondaryVariant">@color/teal_700</item>
            <item name="colorOnSecondary">@color/black</item>
            <!-- Status bar color. -->
            <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
            <!-- Customize your theme here. -->
    
            <item name="toolbarStyle">@style/CustomToolBarStyle</item>
        </style>
    
        <!-- Custom theme of toolBar -->
        <style name="CustomToolBarStyle" parent="Widget.AppCompat.Toolbar">
            <item name="android:background">#FFC0CB</item>
            <item name="titleTextAppearance">@style/CustomTitleTextAppearance</item>
            <item name="subtitleTextAppearance">@style/CustomSubTitleTextAppearance</item>
        </style>
    
        <style name="CustomTitleTextAppearance" parent="TextAppearance.Widget.AppCompat.Toolbar.Title">
            <item name="android:textSize">18sp</item>
            <item name="android:textColor">#ff00ff</item>
        </style>
    
        <style name="CustomSubTitleTextAppearance" parent="TextAppearance.Widget.AppCompat.Toolbar.Subtitle">
            <item name="android:textSize">14sp</item>
            <item name="android:textColor">#808080</item>
        </style>
    
    </resources>
    
  3. Now, open activity_main.xml file. Then, add below code for toolbar –

            <androidx.appcompat.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                app:logo="@drawable/ic_person"
                app:navigationIcon="@drawable/ic_menu"
                app:subtitle="Subtitle"
                app:title="Android ToolBar" />
    
  4. Now, run application. We will get output as below –
    Tutorialwing Kotlin Android Toolbar Using Kotlin With Example

Design Custom XML View in Toolbar

What if we want to add one button in toolBar ? or, add a text ? or add an image in toolBar ?

How can we do it ?

As we already know, Toolbar is subclass of ViewGroup. It means we can place or arrange multiple views inside it. So, we will add one textView and one ImageView inside toolBar. Follow steps below to do it –

  1. Open activity_main.xml file. Then, add below code in it –
        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="?attr/colorPrimary"
            android:minHeight="?attr/actionBarSize"
            android:theme="?attr/actionBarTheme"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent">
    
            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
    
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerVertical="true"
                    android:text="Text Menu" />
    
                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true"
                    android:src="@drawable/ic_menu" />
    
            </RelativeLayout>
    
        </androidx.appcompat.widget.Toolbar>
    

    Notice how we have arranged our views inside toolBar. We can place as many views as we want in this way.

    Finally, code inside activity_main.xml is –

    <?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"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    
        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="?attr/colorPrimary"
            android:minHeight="?attr/actionBarSize"
            android:theme="?attr/actionBarTheme"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent">
    
            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
    
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerVertical="true"
                    android:text="Text Menu" />
    
                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true"
                    android:src="@drawable/ic_menu" />
    
            </RelativeLayout>
    
        </androidx.appcompat.widget.Toolbar>
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    
  2. Run application, we will get output as below –
    Tutorialwing Kotlin Android Toolbar Using Kotlin With Example

    Note: Don’t forget to comment custom styles we have added inside themes.xml file. There is no problem if you don’t do it. However, we have done it in this example.

Different Attributes of Toolbar in XML

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

Set Id of Toolbar

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 Toolbar using android:id attribute like below –

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolBar_ID"
        />

Here, we have set id of Toolbar as toolBar_ID using android:id=”” attribute. So, if we need to reference this Toolbar, we need to use this id – toolBar_ID.
Learn to Set ID of Toolbar Dynamically

Set Width of Toolbar

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

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolBar_ID"
        android:layout_width="wrap_content"
        />

Width can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value (like 20dp, 30dp etc.).
Learn to Set Width of Toolbar Dynamically

Set Height of Toolbar

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

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolBar_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

Height can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value.
Learn to Set Height of Toolbar Dynamically

Set Padding of Toolbar

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

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolBar_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        />

Here, we have set padding of 10dp in Toolbar using android:padding=”” attribute.
Learn to Set Padding of Toolbar Dynamically

Set Margin of Toolbar

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

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolBar_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        />

Here, we have set margin of 10dp in Toolbar using android:layout_margin=”” attribute.
Learn to Set Margin of Toolbar Dynamically

Set Background of Toolbar

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

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolBar_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#ff0000"
        />

Here, we have set background of color #ff0000 in Toolbar using android:background=”” attribute.
Learn to Set Background of Toolbar Dynamically

Set Visibility of Toolbar

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

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolBar_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="gone"
        />

Here, we have set visibility of Toolbar using android:visibility=”” attribute. Visibility can be of three types – gone, visible and invisible
Learn to Set Visibility of Toolbar Dynamically

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

Different Attributes of Android Toolbar Widget

Below are the various attributes that are used to customise android Toolbar Widget. However, you can check the complete list of attributes of Toolbar 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 Toolbar 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

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

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

Leave a Reply