Android Toolbar Example: How to Use Toolbar as ActionBar

Android introduced Toolbar with the release of new operating system Android Lollipop (API 21). Toolbar has replaced the Android Action Bar and we can use it anywhere in our application. Toolbar was introduced in android API 21 (Lollipop 5.0) however we will be able to use this in devices below API 21 also by using appcompact support library.

Android Toolbar Example: How to Use Toolbar as ActionBar

Android Action Bar Tutorial and Example With Option Menu
Android Menus: Best Practice and Awesome Android Menu Libraries

Why Toolbar instead of ActionBar?

Toolbar provides us lots of attributes and we can customize it in our own way than ActionBar. Now we can view multiple toolbars within the screen.

Welcome Toolbar, Goodbye Action Bar

Just follow the following steps to use Toolbar instead Action Bar.

Setup Appcompact Support Library to use Toolbar as ActionBar

 You have to add appcompact support library as a dependency in your build.gradle file before jumping  to our coding part.  Just add compile 'com.android.support:appcompat-v7:22.2.0' in your build.gradle file inside dependencies.

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.2.0'

Change Your App Theme

To use Toolbar as ActionBar you have to use Theme.AppCompact theme, just use Theme.AppCompact.NoActionBar as parent theme.

Your modified code of styles.xml file will look like this:

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.NoActionBar">
        <!-- Customize your theme here. -->

Your AndroidManifest.xml file will look like this:

Adding Toolbar to your Activity Layout

Now you need to add Toolbar to your XML layout. Use the code given below to use Toolbar as Actionbar.

Finally, we have to add two lines of code in our java Activity.

Toolbar toolbar=(Toolbar)findViewById(R.id.toolbar);

Modified code of MainActivity.java file will look like this:

That's all, now run your Toolbar Example application.
Tutorial 40500756738850853
Home item