How to use Toolbar to replace your Actionbar

So a while ago Google released their AppCompat v21 library which brought Material Design to Pre-lollipop devices. In the article announcing that the new AppCompat library was release amoung other things, a new Toolbar widget was introduced as a widget based generalization of the much loved ActionBar.

To use the Toolbar there are two main options; it can either be used to replace the ActionBar or in a layout as a widget on its own. The reason Toolbar can work either way is because it has all of the features of the ActionBar like the abilty to support navigation, to have a title or subtitle, and also to have a logo.

Using the Toolbar to replace an ActionBar is pretty straight forward and begins with making sure that the activity extends ActionBarActivity. Also make sure that the theme for this activity is a child of either Theme.AppCompat.NoActionBar or Theme.AppCompat.Light.NoActionBar. If you are not using the Theme.AppCompat variants then you can alternatively add the following lines to your theme:

<item name="android:windowNoTitle">true</item>
 <item name="windowActionBar">false</item> 

Then just add the Toolbar to your Activities layout:

<android.support.v7.widget.Toolbar  
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:minHeight="?attr/actionBarSize"
    app:theme="@style/ThemeOverlay.AppCompat.ActionBar" />

Set the Toolbar to be your ActionBar via setSupportActionBar:

    Toolbar mToolbar = (Toolbar) findViewById(R.id.my_toolbar);
    setSupportActionBar(mToolbar);

That last part is where all the magic happens because it tells Android to use this Toolbar widget exactly how it would use the SupportActionBar. This means that most of the SupportActionBar methods work so to set the title/subtitle just call:

    getSupportActionBar().setTitle("Toolbar Title");
    getSupportActionBar().setSubtitle("Toolbar Subtitle");

This also means that you can use the same callbacks to create a menu on the Toolbar.
onCreateOptionsMenu and onOptionsItemSelected.

For further information checkout the documentation just to see what all the Toolbar supports. As a general rule, if the Actionbar could do it, the Toolbar can. If you have crazy requirements beyond what is supported by the Toolbar then just remember that the Toolbar is just a fancy ViewGroup so you can add widgets/views just as easily as if it were a LinearLayout.