ToolBar in Android with Example

23 Feb, 2021
In Android applications, Toolbar is a kind of ViewGroup that can be placed in the XML layouts of an activity. It was introduced by the Google Android team during the release of Android Lollipop(API 21). The Toolbar is basically the advanced successor of the ActionBar. It is much more flexible and customizable in terms of appearance and functionality. Unlike ActionBar, its position is not hardcoded i.e., not at the top of an activity. Developers can place it anywhere in the activity according to the need just like any other View in android. Toolbar use material design theme features of Android and thus it provides backward compatibility up to API 7(Android 2.1). One can use the Toolbar in the following two ways:
Use as an ActionBar: In an app, the toolbar can be used as an ActionBar in order to provide more customization and a better appearance. All the features of ActionBar such as menu inflation, ActionBarDrawerToogle, etc. are also supported in Toolbar.Use a standalone Toolbar: It can be used to implement a certain kind of design to an application that can not be fulfilled by an ActionBar. For example, showing a Toolbar at a position other than the top of the activity or showing multiple Toolbars in an activity.
Use as an ActionBar: In an app, the toolbar can be used as an ActionBar in order to provide more customization and a better appearance. All the features of ActionBar such as menu inflation, ActionBarDrawerToogle, etc. are also supported in Toolbar.
Use a standalone Toolbar: It can be used to implement a certain kind of design to an application that can not be fulfilled by an ActionBar. For example, showing a Toolbar at a position other than the top of the activity or showing multiple Toolbars in an activity.
Features supported by the Toolbar are much more focused and customizable than the ActionBar. Following are the components that can be added to make a user-appealing Toolbar:
Navigation button: This element is aligned vertically with respect to the minimum height of the Toolbar. It is used as a guide for switching between other destinations within an app. The appearance of this element can be in many forms such as navigation menu toggle, close, collapse, done, a simple up arrow, or any other kind of glyph required by the app.
Brand logo/App icon: It is one of the most important aspects of an application as it provides a kind of identity. The height of the logo/icon is generally up to the height of the Toolbar but it can be extended as per the need.
Title and Subtitle: The purpose of providing a title to the Toolbar is to give information regarding the current position within the navigation hierarchy of an app. The Subtitle is used to indicate any kind of extended information about the content.
ActionMenuView: It is similar to the Action Buttons in ActionBar that display some important actions/elements of the app which may be required to the users frequently. Elements of this menu are placed to the end(rightmost side) of the Toolbar.
Multiple Custom Views: Android allows developers to add one or more Views such as ImageView, TextView, etc. within the layout of the Toolbar. These views are treated as children of the Toolbar layout and their position can be adjusted according to the need.           
Working with Toolbar is very similar to any operate a View. One can easily assign constraints, change height and width, choose a background color, and much more. To carry out these same tasks in ActionBar, extra lines of code is needed to be written. Here is an example to use the Toolbar as an ActionBar. Following is the step by step method which covers the complete procedure.
Note: Following steps are performed on Android Studio version 4.0
Step 1: Assure the presence of these dependencies in app-level build.gradle file
In order to use Toolbar as an ActionBar, one has to include the following dependencies in the build.gradle file of app module. These dependencies might be already present in the file but it always good to check it once.
dependencies {
 .....
.....
 implementation ‘androidx.appcompat:appcompat:1.2.0’
implementation ‘com.google.android.material:material:1.2.1’
}
 Step 2: Default settings
Open the activity_main.xml file of the application and switch to its Design window. The preview of the activity will not contain any ActionBar or Toolbar at this point. However, on running the application, the default format of ActionBar will appear on top of the activity which will display only the name of the application. 
Step 3: Adding Toolbar in activity_main.xml file
Search the Toolbar View from the Palette menu present at the top left portion of the Design window. Drag and place it as a child of ConstraintLayout. To make its appearance similar to ActionBar, add the AppBarLayout in the activity_main.xml file in such a manner that the Toolbar becomes its child. Add the top, left, and right constraint of the AppBarLayout. By running the application at this point in time, one can observe both Toolbar and ActionBar(as it is the default setting) on top of the activity. Below is the code of the activty_main.xml file that will produce the discussed output.
XML
<?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">      <com.google.android.material.appbar.AppBarLayout        android:layout_width="0dp"        android:layout_height="wrap_content"        app:layout_constraintEnd_toEndOf="parent"        app:layout_constraintStart_toStartOf="parent"        app:layout_constraintTop_toTopOf="parent">          <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"            tools:layout_editor_absoluteX="0dp"            tools:layout_editor_absoluteY="0dp" />      </com.google.android.material.appbar.AppBarLayout>      <TextView        android:id="@+id/textView"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Hello World!"        app:layout_constraintBottom_toBottomOf="parent"        app:layout_constraintLeft_toLeftOf="parent"        app:layout_constraintRight_toRightOf="parent"        app:layout_constraintTop_toTopOf="parent" />  </androidx.constraintlayout.widget.ConstraintLayout>
Output:
Step 4: Remove ActionBar
The easiest way to remove the ActionBar from the entire app is to change the default code of the styles.xml file. The theme of the parent/base application must be changed to Theme.AppCompat.Light.NoActionBar. Below is the code that will make the desired changes.
XML
<resources>    <!-- Base application theme. -->    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">        <!-- Customize your theme here. -->        <item name="colorPrimary">@color/colorPrimary</item>        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>        <item name="colorAccent">@color/colorAccent</item>    </style>  </resources>
Output:
Step 5: Using Toolbar as ActionBar
The Toolbar will not display the application title unless it is declared as an ActionBar. To make the desired change, the ID of the Toolbar must be passed as an argument in the setSupportActionBar() method written inside the MainActivity file. Below is the code to do the same.
Java
Kotlin
import androidx.appcompat.app.AppCompatActivity;import androidx.appcompat.widget.Toolbar;import android.os.Bundle;import android.view.View;import android.widget.TextView;  public class MainActivity extends AppCompatActivity {      @Override    protected void onCreate( Bundle savedInstanceState ) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);          // assigning ID of the toolbar to a variable        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);          // using toolbar as ActionBar        setSupportActionBar(toolbar);      }}
import android.os.Bundleimport android.view.Viewimport android.widget.TextViewimport androidx.appcompat.app.AppCompatActivityimport androidx.appcompat.widget.Toolbar  class MainActivity : AppCompatActivity() {      override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)        setContentView(R.layout.activity_main)          // assigning ID of the toolbar to a variable        val toolbar = findViewById<View>(R.id.toolbar) as Toolbar          // using toolbar as ActionBar        setSupportActionBar(toolbar)   }}
Output:
Step 6: Customize the Toolbar
Each and every component/element that will be displayed on the Toolbar is customizable. The text of the application title, its color, background color of the Toolbar can be easily modified through XML attributes. While placing various kinds of Views in the Toolbar such as ImageView, Vectors, TextView, etc. one must have the capability to control its position and dimensions. In order to do so, ConstraintLayout must be added under the AppBarLayout. With this, the hierarchy of Component Tree becomes parent ConstraintLayout of activity, after that AppBarLayout, then again ConstraintLayout as its child and finally the Toolbar view. 
Further, a TextView and two ImageView are added in the same hierarchy as that of Toolbar. For the content of ImageView, vectors are used in this example. Right-click on the res folder and select new then Vector Asset. Click on the icon written beside Clip Art and select the desired image. Don’t forget to give a unique name to that vector file as it will be easy to remember and to be used in code. Click on Next and then Finish.
The code of the activity_main.xml file given below will add two ImageView, one TextView, custom title, and background color in the Toolbar.
XML
<?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"    android:background="#168BC34A"    tools:context=".MainActivity">      <!-- AppBar layout for using Toolbar as AppBar -->    <com.google.android.material.appbar.AppBarLayout        android:id="@+id/appBarLayout"        android:layout_width="0dp"        android:layout_height="wrap_content"        app:layout_constraintEnd_toEndOf="parent"        app:layout_constraintStart_toStartOf="parent"        app:layout_constraintTop_toTopOf="parent">          <androidx.constraintlayout.widget.ConstraintLayout            android:layout_width="match_parent"            android:layout_height="match_parent">              <!-- ToolBar widget -->            <androidx.appcompat.widget.Toolbar                android:id="@+id/toolbar"                android:layout_width="match_parent"                android:layout_height="wrap_content"                android:background="#0F9D58"                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="  GfG | Tool bar"                app:titleTextColor="#ffff" />              <!-- Right most TextView -->            <TextView                android:id="@+id/textView2"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:layout_marginEnd="10dp"                android:text="0"                android:textColor="#ffff"                android:textSize="18sp"                android:textStyle="bold"                app:layout_constraintBottom_toBottomOf="parent"                app:layout_constraintEnd_toEndOf="@+id/toolbar"                app:layout_constraintTop_toTopOf="parent" />              <!-- Right most ImageView -->            <ImageView                android:id="@+id/imageView2"                android:layout_width="wrap_content"                android:layout_height="24dp"                android:layout_marginEnd="9dp"                app:layout_constraintBottom_toBottomOf="parent"                app:layout_constraintEnd_toStartOf="@+id/textView2"                app:layout_constraintTop_toTopOf="parent"                app:srcCompat="@drawable/build_icon" />              <!-- ImageView beside title of ToolBar -->            <ImageView                android:id="@+id/imageView"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:layout_marginEnd="150dp"                app:layout_constraintBottom_toBottomOf="parent"                app:layout_constraintEnd_toStartOf="@+id/imageView2"                app:layout_constraintTop_toTopOf="parent"                app:srcCompat="@drawable/android_icon"                app:tint="#ffff" />          </androidx.constraintlayout.widget.ConstraintLayout>      </com.google.android.material.appbar.AppBarLayout>      <!-- TextView of the Activity -->    <TextView        android:id="@+id/textView"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Hello Geek!!"        android:textSize="24sp"        android:textStyle="bold"        app:layout_constraintBottom_toBottomOf="parent"        app:layout_constraintLeft_toLeftOf="parent"        app:layout_constraintRight_toRightOf="parent"        app:layout_constraintTop_toTopOf="parent" />  </androidx.constraintlayout.widget.ConstraintLayout>
Output:
Step 7: Adding a logo and some more customization
As mentioned earlier, the developers add a logo/icon to give a unique identity to the application. While using Toolbar as an ActionBar, the logo of the application is designed exactly the same as in the ActionBar. One has to add the required code in the MainActivity file in order to add the logo in the Toolbar. Moreover, the Views added in the Toolbar can be programmed to perform some operations in the same manner as they are present in the activity. In this example, the TextView added in the Toolbar will increment its value by one on every click. Below the complete code to carry out this task.
Java
Kotlin
import androidx.appcompat.app.AppCompatActivity;import androidx.appcompat.widget.Toolbar;import android.os.Bundle;import android.view.View;import android.widget.TextView;  public class MainActivity extends AppCompatActivity {      TextView textView;    int count = 0;      @Override    protected void onCreate( Bundle savedInstanceState ) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);          // assigning ID of the toolbar to a variable        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);          // using toolbar as ActionBar        setSupportActionBar(toolbar);            // Display application icon in the toolbar        getSupportActionBar().setDisplayShowHomeEnabled(true);        getSupportActionBar().setLogo(R.drawable.app_icon);        getSupportActionBar().setDisplayUseLogoEnabled(true);          // assigning ID of textView2 to a variable        textView = (TextView) findViewById(R.id.textView2);            // "on click" operations to be performed        textView.setOnClickListener(new View.OnClickListener() {            @Override              // incrementing the value of textView            public void onClick( View view ) {                count++;                textView.setText("" + count);            }        });      }}
import android.os.Bundleimport android.view.Viewimport android.widget.TextViewimport androidx.appcompat.app.AppCompatActivityimport androidx.appcompat.widget.Toolbar  class MainActivity : AppCompatActivity() {    var textView: TextView? = null    var count = 0    override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)        setContentView(R.layout.activity_main)          // assigning ID of the toolbar to a variable        val toolbar = findViewById<View>(R.id.toolbar) as Toolbar          // using toolbar as ActionBar        setSupportActionBar(toolbar)            // Display application icon in the toolbar        supportActionBar!!.setDisplayShowHomeEnabled(true)        supportActionBar!!.setLogo(R.drawable.app_icon)        supportActionBar!!.setDisplayUseLogoEnabled(true)          // assigning ID of textView2 to a variable        textView = findViewById<View>(R.id.textView2) as TextView            // "on click" operations to be performed        textView!!.setOnClickListener {            count++            textView!!.text = "" + count        }    }}
No hardcoded position in the app.
Flexible design and much more customizable than ActionBar.
Use latest Android Material theme
Provides backward compatibility up to Android 2.1(API 7).
Android-Bars
Technical Scripter 2020
Android
Java
Kotlin
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.