Material Design Component Top App Bar in Android
Material Design Components (MDC Android) offers designers and developers a way to implement Material Design in their Android applications. Developed by a core team of engineers and UX designers at Google, these components enable a reliable development workflow to build beautiful and functional Android applications. Material design in Android is one of the key features that attracts and engages the customer towards the application. This is a special type of design, which is guided by Google. So in this article, it has been demonstrated how to use Material Design Component Top App bar. Have a look at the following image to get an overview of the discussion.
Create an empty activity project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.
Add Required Dependency
Include google material design components dependency in the build.gradle file. After adding the dependencies don’t forget to click on the “Sync Now” button present at the top right corner.
Note that while syncing your project you need to be connected to the network and make sure that you are adding the dependency to the app-level Gradle file as shown below.
Why Top App Bar used?
The top app bar appears on top of every activity of the application and disappears when scrolled. The top app bar displays the title of the activity and selected primary actions to be taken on the particular activity or the screen in the application. It can also be used for branding, screen titles, navigation, and actions.
Anatomy of Top Action Bar
In the above anatomy of Material Design Top App bar Navigation Icon, Title, Action Menu, Overflow Menu are optional.
Steps to Implement the MDC Top App Bar in Android
Step 1: Creating menu items for Top App Bar
Create a menu resource folder inside the res folder invokes the following code inside the top_app_bar_menu.xml file:
Step 2: Working with the activity_main.xml file
The main layout of the application contains only the top bar. First of all the AppBarLayout needs to be nested inside the coordinator layout and inside the AppBarLayout, MaterialToolbar needs to be invoked. And the size of the MaterialToolbar needs to be the size of actionBarSize. To implement the same invoke the following code inside the activity_main.xml file.
Step 3: Working with the MainActivity.kt file
In the MainActivity.kt file, a simple on menu item click listener is assigned to the instance of the material toolbar. To implement the same invoke the following code. However, one can also implement the navigation drawer for the toolbar, refer to Navigation Drawer in Android.