Next lesson playing in 5 seconds

Cancel
  • Overview
  • Transcript

2.2 Create a Toolbar

A toolbar is one of the most prominent features of a Material Design app. In this lesson, you’ll learn how to create it by using the AppCompat Toolbar widget.

Related Links

2.2 Create a Toolbar

Hello, and welcome back. In the previous lesson you saw that we chose a material design team that doesn't have an action bar. We just set a team because creating a toolbar manually gives us a lot more control over how it behaves and interacts with the other UI widgets of the activity. So in this lesson we'll be creating a toolbar for our main activity. Let's start by opening the layout file of main activity. To add a tool bar here all we need to do is add a tool bar widget. Its width must be match_parent. Its height however must be a special value called actionBarSize. This tool must have an elevation of 4dp according to the material design spec. We must now associate a theme with this toolbar. So, set the value of the theme attribute to @style/ThemeOverlay.AppCompat.Dark.Action- Bar. Next, we must associate a pop up team with this tool bar. In order to do that however we must add the application name space to this xml file. And now we can specify the pop up team we want to use. This can be Themeoverlay.AppCompat.Light, next set its ID to toolbar. This toolbar must be at the top of the activity. So set layout aligned parent top to true. Finally we must give this toolbar a color. So use the background attribute. Instead of specifying a color manually, we can use color primary which we specified during the material design teams configuration. We must now position this list view below the toolbar. You can use the layout below attribute to do that. If you switch to the design mode, you can see that there is a little gap between the toolbar and the corners of the screen, we don't want that. So you can just remove this padding mentioned here. The toolbar looks good now. So we don't need to make any more changes in this layout file, open the main activity class to complete the toolbars configuration. Add the toolbar as a member variable of this class, and then initialize it inside the onCreate method using findViewById. At this point we can assign the toolbar, as the action bar of this activity using the setSupport.ActionBar method You can press the run button now to take a look at the toolbar. As you can see our activity has a toolbar and the old fashioned menu has been replaced automatically with an overflow menu. You now know how to create and use a toolbar. In the next lesson, we are going to add a navigation drawer to our activity. Thanks for watching.

Back to the top