ToolBar in Android | AndroidMonks

ToolBar in Android | AndroidMonks

The toolbar in Android was released as part of the API 21 release, and it contains a lot of flexible components within it. The more general idea of an Action Bar now called as App Bar (The bar at the top of an Application) can be replaced by this ToolBar. The advantage, however, is that ToolBars can be placed at any arbitrary position without respect to the View hierarchy in the layout.

According to the Docs, “A Toolbar is a generalization of foraction bars use within application layouts. While an action bar is traditionally part of an opaqueActivity's window decor controlled by the framework, a Toolbar may be placed at any arbitrary level of nesting within a view hierarchy. An application may choose to designate a Toolbar as the action bar for an Activity using the methodsetActionBar()“.

A sample Toolbar is given below,

Sample Toolbar acting as a Action Bar
Sample Toolbar acting as an Action Bar

ToolBar Elements

  • A navigation button. This may be an Up arrow, navigation menu toggle, close, collapse, done or another glyph of the app’s choosing. This button should always be used to access other navigational destinations within the container of the Toolbar and its signified content or otherwise leave the current context signified by the Toolbar. The navigation button is vertically aligned within the Toolbar’s minimum heightif set.
  • A branded logo image. This may extend to the height of the bar and can be arbitrarily wide.
  • A title and subtitle. The title should be a signpost for the Toolbar’s current position in the navigation hierarchy and the content contained there. The subtitle, if present should indicate any extended information about the current content. If an app uses a logo image it should strongly consider omitting a title and subtitle.
  • One or more custom views. The application may add arbitrary child views to the Toolbar. They will appear at this position within the layout. If a child view’sToolbar.LayoutParams indicates a Gravity value ofCENTER_HORIZONTAL the view will attempt to center within the available space remaining in the Toolbar after all other elements have been measured.
  • An.action menu The menu of actions will pin to the end of the Toolbar offering a few frequent, important or typical actions along with an optional overflow menu for additional actions. Action buttons are vertically aligned within the Toolbar’s minimum heightif set.

ToolBar – Basic Implementation

Make sure you are using the below line in your App Gradle

implementation 'com.android.support:design:28.0.0'

You can go on and implement a simple ToolBar with the below definition.

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/colorPrimary"
    android:theme="@style/ThemeOverlay.AppCompat.Dark">
</android.support.v7.widget.Toolbar>

The View just like any other view takes the default attribute layout_width and layout_height. On top of that, there are also some important attributes to be given as well. There is a list of attributes that the ToolBar layout specifically takes, they are

ToolBar Layout – Attributes List

android:logo  – ToolBar layout provides the property of adding a Logo on the App Bar. This takes a drawable value to set as a logo

android:subtitle – The Subtitle value can be given in navigationMode=”normal”.

android:title – The Title associated with the item.

android:titleTextColor – Applies a text color to the Title.

android:popupTheme – Reference to a theme that should be used to inflate popups shown by widgets in the toolbar.

android:navigationIcon – Icon drawable to use for the navigation button located at the start of the toolbar. The icon is generally to show a Menu that can be opened.

android:collapseContentDescription – Text to set as the content description for the collapse button

To view the entire list of all the attributes available for ToolBar layout you can check the post here.

ToolBar – Public Methods

The list of important Public Methods of the Toolbar is,

getLogo() – Returns the logo, which is an object of the Drawable.

getLogoDescription() – Returns the Description given to the Logo.

getTitle()/getSubtitle() – Returns the Title/Subtitle of the given Toolbar.

inflateMenu(int resId) – Inflate a menu resource into this toolbar.

onTouchEvent(MotionEvent ev) – This callback is useful to handle the Touch Motions Events.

setLogo(int resId) – Sets a Logo Drawable from the given Resource Id.

setTitle(CharSequence title)/setTitle(int resId) – Setter to set the values of the Title/Subtitle to the given ToolBar

ToolBar Example Application – Android Studio

Below is a short and clear example of creating a ToolBar using Android Studio IDE.

Adding a Notification Menu button(A 3 dotted menu on the side)

Even before we start with the example, make sure you follow these linearly. The example portion is arranged in such a way to help you go through this without the haphazard creation of files here and there.

Before you start: Make sure you have the below dependency in your gradle. Sync the project before you proceed.

implementation 'com.android.support:design:28.0.0'
Step 1: Create your Layout

In this step, we will create a simple Layout. Nothing fancy, just the one tag below.

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/colorPrimary"
    android:theme="@style/ThemeOverlay.AppCompat.Dark"
    app:logo="@drawable/tick">

</android.support.v7.widget.Toolbar>

I am making use of some of the attributes mentioned above.

Here app:logo(Which is optional) is set to a drawable tick.png which is present in my res>drawable folder.

Drawable Tick for toolbar logo
Drawable Tick for toolbar logo
Step 2: Creating a Menu File

The objective of this example is to create a Menu. You can create a menu layout inside the res>menu folder like given below.

Create a directory named menu

Create a directory named menu
Create a directory named menu

Create a Menu Resource file inside this menu directory

Menu file inside menu directory
Menu file inside menu directory

I already have one created called navigation. We will be adding the menu items inside this file.

Step 3 : Add items to your Menu

Fill out your Menu file with the required items. I am adding a total of 3 items inside like below.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/navigation_home"
        android:title="@string/title_home" />

    <item
        android:id="@+id/navigation_dashboard"
        android:title="@string/title_dashboard" />

    <item
        android:id="@+id/navigation_notifications"
        android:title="@string/title_notifications" />
</menu>

Upon completion of creating the Menu. Time to create our Activity.

Step 4: Create ToolBar Activity

The ToolBarActivity.class will be the Activity to hold our tool_bar layout. Create a simple Activity and setContentView the tool_bar layout like below.

public class ToolBarActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tool_bar);
        //getting the toolbar
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("AndroidMonks");
        setSupportActionBar(toolbar);

    }
}

In onCreate Activity, we will be putting our ToolBar in place of the ActionBar(One of the property of ToolBar is that, it can be placed anywhere on the layout, can also replace the ActionBar). The setSupportActionBar method is very important to make the ToolBar act as a ActionBar which will be responsible for holding the Menu.

We will extend this to add the Menu we created in Step 3. Add the following methods(These are menu inflation callbacks).

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater menuInflater = getMenuInflater();
    menuInflater.inflate(R.menu.navigation, menu);
    return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch(item.getItemId()){
        case R.id.navigation_home:
            Toast.makeText(this, "You clicked Home", Toast.LENGTH_SHORT).show();
            break;

        case R.id.navigation_dashboard:
            Toast.makeText(this, "You clicked Dashboard", Toast.LENGTH_SHORT).show();
            break;

        case R.id.navigation_notifications:
            Toast.makeText(this, "You clicked Notification", Toast.LENGTH_SHORT).show();
            break;
    }
    return true;
}

In onCreateOptionsMenu() method, we make use of the MenuInflater class to inflate the Menu file we created in Step 3.

Once the inflated Menu is set, it by default places it in our ActionBar(Which is replaced by the ToolBar like we saw above).

We handle the Click of the Items of the Menu using the onOptionsItemSelected() (Callback to handle the items click callback).

Upon creating this, ToolBarActivity looks like below.

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

public class ToolBarActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tool_bar);
        //getting the toolbar
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("AndroidMonks");
        setSupportActionBar(toolbar);

    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.navigation, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch(item.getItemId()){
            case R.id.navigation_home:
                Toast.makeText(this, "You clicked Home", Toast.LENGTH_SHORT).show();
                break;

            case R.id.navigation_dashboard:
                Toast.makeText(this, "You clicked Dashboard", Toast.LENGTH_SHORT).show();
                break;

            case R.id.navigation_notifications:
                Toast.makeText(this, "You clicked Notification", Toast.LENGTH_SHORT).show();
                break;
        }
        return true;
    }
}
Step 5: Run the App in your AVD

Upon running the Application in your AVD(Or a physical device) the below Application is created.

Toolbar application
Toolbar application

This is just scratching the top of the surface when it comes to creating a simple ToolBar application. Drop in any comments you have in the section below.

“Learn and Be Curious”

Leave a Comment

Your email address will not be published. Required fields are marked *