Android Toolbar for AppCompatActivity

Nick Babich
2 min readFeb 3, 2016

The Android Toolbar has replaced the old action bar. It was introduced in API 21 (Android 5.0 Lollipop). In this tutorial we are going to implement it using the support v7 library. Our goal is to implement a toolbar with icons which is supported by older versions of Android as well.

Step 1: Check Gradle dependencies

Open your build.gradle (Module:app) for your project and make sure you have a following dependency:

Step 2: Modify your layout.xml file and add a new style

Go to the res / layout / activity_main.xml for your project and add your toolbar as layout widget:

Next add a new style for you toolbar. Go to the res / values / styles.xml. Add a simple color for a background:

Step 3: Add a menu for the toolbar

Go to the res / menu / menu_main.xml for your project and add a new menu with a single element (e.g. user’s favorite pages):

Image for a icon’s drawable was taken from the Google Material Design Icons.

Step 4: Add toolbar to the activity

Go to the java / MainActivity.java. Modify the class to initialize your toolbar. Make sure you import a toolbar library from v7 support libraries.

Step 5: Inflate (Add) the menu to the toolbar

This is the final step. Here we just inflate the menu and handle click on our action_favorite button — a simple text message appears as result of click.

Our result should look like this.

And when we click on this icon we will see a Toast with information ‘Action clicked’.

This is a basic example of adding a toolbar to an Android application. Please comment below with your queries and suggestion.

Thank you!

--

--