Setting Up the App Bar in Android

In its most basic form, the action bar displays the title for the activity on one side and anoverflow menu on the other. Even in this simple form, the app bar provides useful information to the users, and helps to give Android apps a consistent look and feel.

Figure 1. An app bar with the app title and overflow menu.

Beginning with Android 3.0 (API level 11), all activities that use the default theme have an ActionBar as an app bar. However, app bar features have gradually been added to the native ActionBar over various Android releases. As a result, the native ActionBar behaves differently depending on what version of the Android system a device may be using. By contrast, the most recent features are added to the support library’s version of Toolbar, and they are available on any device that can use the support library.

For this reason, you should use the support library’s Toolbar class to implement your activities’ app bars. Using the support library’s toolbar helps ensure that your app will have consistent behavior across the widest range of devices. For example, the Toolbar widget provides a material designexperience on devices running Android 2.1 (API level 7) or later, but the native action bar doesn’t support material design unless the device is running Android 5.0 (API level 21) or later.

Add a Toolbar to an Activity

These steps describe how to set up a Toolbar as your activity’s app bar:

Add the v7 appcompat support library to your project, as described in Support Library Setup.

Make sure the activity extends AppCompatActivity:

publicclassMyActivityextendsAppCompatActivity{// ...}

Note: Make this change for every activity in your app that uses a Toolbar as an app bar.

In the app manifest, set the <application> element to use one of appcompat’s NoActionBar themes. Using one of these themes prevents the app from using the native ActionBar class to provide the app bar. For example:

Your app now has a basic action bar. By default, the action bar contains just the name of the app and an overflow menu. The options menu initially contains just the Settings item. You can add more actions to the action bar and the overflow menu, as described in Adding and Handling Actions.

Use App Bar Utility Methods

Once you set the toolbar as an activity’s app bar, you have access to the various utility methods provided by the v7 appcompat support library’sActionBar class. This approach lets you do a number of useful things, like hide and show the app bar.

To use the ActionBar utility methods, call the activity’s getSupportActionBar() method. This method returns a reference to an appcompat ActionBarobject. Once you have that reference, you can call any of the ActionBar methods to adjust the app bar. For example, to hide the app bar, callActionBar.hide().