How to replace the Android ActionBar with Toolbar

With Android 5.0 Lollipop and Material Design, Android introduced the Toolbar as a replacement for the ActionBar. This post will teach you how to replace the Android ActionBar with Toolbar.

This replacement brings a few benefits, including but not limited to:

  • The toolbar is not attached to the Activity window, but can be used anywhere in the View hierarchy.
  • Toolbars can have both titles and subtitles.
  • You can still use an ActionMenu for the FIT (Frequent, Important, Typical) features.

However, some developers such as myself struggled with how to replace the ActionBar with a Toolbar. This task is not as daunting as it looks, and you can achieve the appearance below in just a few steps.

Replace ActionBar With Toolbar

Add the support library dependency

First, you will need to add the following dependency to your build.gradle file to have access to the support library classes:

Tell Android not to use the ActionBar

By default, if your Activity extends ActionBarActivity or AppCompatActivity, you will have an ActionBar at the top. Before you can replace it with your Toolbar, you need to make sure it doesn’t appear at all. This can be handled in your styles.xml file by adding the following two items inside your theme:

Design your Toolbar

The next step is to design the Toolbar layout. In this sample app, we will not be using any custom Views in the Toolbar. All we have to do to it is set it’s minimum height attribute to actionBarSize (this way we enable ourselves to expanding the Toolbar if we do add views, but at a minimum keep it the same height as the ActionBar), and set the Theme and background color:

Include the layout in your Activity’s XML

In order for the Toolbar to actually appear in the Activity, you will need to include it in the XML file by using the <include> tag. In our example, we just set the Toolbar to be at the top of the layout just like the ActionBar was:

Replace the ActionBar programmatically

In the beginning we wrote code to tell the app not to use the ActionBar. Great, but… how does it know to use the Toolbar? We put it in the XML, but if you ran the app as it is you’ll see that the Toolbar appears, but is blank and missing the Activity title. In order for our app to use the Toolbar as a replacement for the ActionBar, we just add the following two lines in onCreate() of the Activity:

And that’s it! You can now successfully replace the ActionBar with a Toolbar in Android apps!

You can find the code for this sample application on my Github page.

Share this post...
Share on Reddit0Share on Google+0Tweet about this on TwitterShare on LinkedIn0Share on Facebook0

Leave a Reply