1. Code
  2. Mobile Development
  3. Android Development

How to Code a Navigation Drawer for an Android App

Scroll to top
Final product imageFinal product imageFinal product image
What You'll Be Creating

The Material Design team at Google defines the functionality of a navigation drawer in Android as follows:

The navigation drawer slides in from the left and contains the navigation destinations for your app.

An example of a popular Android app that implements the navigation drawer menu design is the Inbox app from Google, which uses a navigation drawer to navigate different application sections. You can check it yourself by downloading the Inbox app from the Google Play store if you don't already have it on your device. The screenshot below shows Inbox with the navigation drawer pulled open.

navigation drawer androidnavigation drawer androidnavigation drawer android

The user can view the navigation drawer when they swipe a finger from the left edge of the activity. They can also find it from the home activity (the top level of the app) by tapping the app icon (also known as the Android "hamburger" menu) in the action bar. 

Note that if you have many different destinations (more than six, say) in your app, it's recommended that you use a navigation drawer menu design.

In this post, you'll learn how to display navigation items inside a navigation drawer in Android. We'll cover how to use Jetpack navigation to perform this task. As a bonus, you'll also learn how to use the Android Studio templates feature to bootstrap your project with a navigation drawer quickly.

Prerequisites

To be able to follow this Android Studio navigation drawer tutorial, you'll need:

Create an Android Studio Project

Fire up Android Studio and create a new project (you can name it NavigationDrawer) with an empty activity called MainActivity. Make sure to also choose the Kotlin language.

Create empty activityCreate empty activityCreate empty activity

Add Project Dependencies

Support for navigation requires some dependencies. Open the app build.gradle file and add the following dependencies.

1
dependencies {
2
    def lifecycle_version = "2.2.0"
3
    implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"
4
    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
5
    ...
6
}

Also add the material library to the project.

1
dependencies {
2
    ...
3
    implementation "com.google.android.material:material:$version"
4
    ...
5
}

Sync the project files for the changes to take effect.

Create the DrawerLayout 

To display the drawer icon on all destinations in our app, we will use the DrawerLayout component. Open main_acivity.xml and add DrawerLayout as the root view. The drawer layout will host two child views, NavHostFragment and NavigationView.

1
<?xml version="1.0" encoding="utf-8"?>
2
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="https://schemas.android.com/apk/res/android"
3
    xmlns:app="http://schemas.android.com/apk/res-auto"
4
    xmlns:tools="http://schemas.android.com/tools"
5
    android:id="@+id/drawer_layout"
6
    android:layout_width="match_parent"
7
    android:layout_height="match_parent"
8
    android:fitsSystemWindows="true"
9
    tools:openDrawer="start">
10
11
<!--TOOLBAR HERE-->
12
13
14
<!--NavHostFragment HERE-->
15
       
16
<!--NavigationView HERE-->
17
       
18
</androidx.drawerlayout.widget.DrawerLayout>
19

Here we created a DrawerLayout widget with the id drawer_layout. The tools:openDrawer property is used to display the navigation drawer toggle when the XML layout is open in Android Studio design view. 

The official documentation says the following about DrawerLayout:

DrawerLayout acts as a top-level container for window content that allows for interactive "drawer" views to be pulled out from one or both vertical edges of the window.

After adding the DrawerLayout widget, we included a child layout, app_bar_main.xml which points to the toolbar layout.

1
<!--main_activity.xml-->
2
<?xml version="1.0" encoding="utf-8"?>
3
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
4
    xmlns:app="http://schemas.android.com/apk/res-auto"
5
    xmlns:tools="http://schemas.android.com/tools"
6
    android:id="@+id/drawer_layout"
7
    android:layout_width="match_parent"
8
    android:layout_height="match_parent"
9
    android:fitsSystemWindows="true"
10
    tools:openDrawer="start">
11
12
    <include
13
        layout="@layout/app_bar_main"
14
        android:layout_width="match_parent"
15
        android:layout_height="match_parent" />
16
17
18
<!--NavHostFragment HERE-->
19
       
20
<!--NavigationView HERE-->
21
       
22
</androidx.drawerlayout.widget.DrawerLayout>
23

Here is my app_bar_main.xml resource file. This file has a CoordinatorLayout, an AppBarLayout, and a Toolbar widget. 

1
<!--tool_bar_layout.xml-->
2
<?xml version="1.0" encoding="utf-8"?>
3
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
4
    xmlns:app="http://schemas.android.com/apk/res-auto"
5
    xmlns:tools="http://schemas.android.com/tools"
6
    android:layout_width="match_parent"
7
    android:layout_height="match_parent"
8
    tools:context=".MainActivity">
9
10
    <com.google.android.material.appbar.AppBarLayout
11
        android:layout_width="match_parent"
12
        android:layout_height="wrap_content"
13
        android:theme="@style/Theme.NavigationDrawer.AppBarOverlay">
14
15
        <androidx.appcompat.widget.Toolbar
16
            android:id="@+id/toolbar"
17
            android:layout_width="match_parent"
18
            android:layout_height="?attr/actionBarSize"
19
            android:background="?attr/colorPrimary"
20
            app:popupTheme="@style/Theme.NavigationDrawer.PopupOverlay" />
21
22
    </com.google.android.material.appbar.AppBarLayout>
23
24
</androidx.coordinatorlayout.widget.CoordinatorLayout>

Create a Navigation Graph

navigation graph is an XML resource file that contains all of your app's destinations and actions, and these destinations are connected via actions. Below is an example of a navigation graph showing five fragments.

Nav graph showing 5 screensNav graph showing 5 screensNav graph showing 5 screens
Enter Nav graph showing 5 screens

To add a navigation graph, right-click on the res directory and select New > Android Resource File. In the next dialog, select Navigation as the Resource Type, and click OK. A new XML file, nav_graph.xml, will be created in the Navigation folder, as shown below.

create a navigation graphcreate a navigation graphcreate a navigation graph
Create navigation graph

Add NavHostFragment 

A navigation host fragment acts as a host for the app's fragments and swaps fragments in and out as necessary when the user moves from one destination to the other. These destinations have to be defined in the navigation graph.

Add NavHostFragment to the main_activity.xml file and reference the navGraph.

1
<!--main_activity.xml-->
2
<?xml version="1.0" encoding="utf-8"?>
3
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
4
    xmlns:app="http://schemas.android.com/apk/res-auto"
5
    xmlns:tools="http://schemas.android.com/tools"
6
    android:id="@+id/drawer_layout"
7
    android:layout_width="match_parent"
8
    android:layout_height="match_parent"
9
    android:fitsSystemWindows="true"
10
    tools:openDrawer="start">
11
12
    <include
13
        layout="@layout/app_bar_main"
14
        android:layout_width="match_parent"
15
        android:layout_height="match_parent" />
16
17
18
<androidx.constraintlayout.widget.ConstraintLayout
19
    android:layout_width="match_parent"
20
    android:layout_height="match_parent">
21
22
    <fragment
23
        android:id="@+id/nav_host_fragment"
24
        android:name="androidx.navigation.fragment.NavHostFragment"
25
        android:layout_width="match_parent"
26
        android:layout_height="match_parent"
27
        app:defaultNavHost="true"
28
        app:layout_constraintLeft_toLeftOf="parent"
29
        app:layout_constraintRight_toRightOf="parent"
30
        app:layout_constraintTop_toTopOf="parent"
31
        app:navGraph="@navigation/nav_graph" />
32
</androidx.constraintlayout.widget.ConstraintLayout>
33
       
34
<!--NavigationView HERE-->
35
       
36
</androidx.drawerlayout.widget.DrawerLayout>
37

Add Fragments to the Destination Graph

Fragments represent all the destinations of your app. In our case, we will add three fragments to the navigation graph. Right-click the navigation folder and open nav_graph.xml. To add a fragment, click on Create New Destination and fill out the rest of the details.

Add fragment to navigation graphAdd fragment to navigation graphAdd fragment to navigation graph
Add fragment to navigation graph

Repeat the same steps and create two additional fragments, the profile fragment and the settings fragment. Your navigation graph should now look like this.

navigation graphnavigation graphnavigation graph

Add a NavigationView Component

Finally, let's create  a NavigationView widget. The official documentation says the following about NavigationView:

NavigationView represents a standard navigation menu for application. The menu contents can be populated by a menu resource file.

Open main_activity.xml and add the NavigationView.

1
<!--main_activity.xml-->
2
<?xml version="1.0" encoding="utf-8"?>
3
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
4
    xmlns:app="http://schemas.android.com/apk/res-auto"
5
    xmlns:tools="http://schemas.android.com/tools"
6
    android:id="@+id/drawer_layout"
7
    android:layout_width="match_parent"
8
    android:layout_height="match_parent"
9
    android:fitsSystemWindows="true"
10
    tools:openDrawer="start">
11
12
    <include
13
        layout="@layout/app_bar_main"
14
        android:layout_width="match_parent"
15
        android:layout_height="match_parent" />
16
17
18
<androidx.constraintlayout.widget.ConstraintLayout
19
    android:layout_width="match_parent"
20
    android:layout_height="match_parent">
21
22
    <fragment
23
        android:id="@+id/nav_host_fragment"
24
        android:name="androidx.navigation.fragment.NavHostFragment"
25
        android:layout_width="match_parent"
26
        android:layout_height="match_parent"
27
        app:defaultNavHost="true"
28
        app:layout_constraintLeft_toLeftOf="parent"
29
        app:layout_constraintRight_toRightOf="parent"
30
        app:layout_constraintTop_toTopOf="parent"
31
        app:navGraph="@navigation/nav_graph" />
32
</androidx.constraintlayout.widget.ConstraintLayout>
33
       
34
<com.google.android.material.navigation.NavigationView
35
        android:id="@+id/nav_view"
36
        android:layout_width="wrap_content"
37
        android:layout_height="match_parent"
38
        android:layout_gravity="start"
39
        android:fitsSystemWindows="true"
40
        app:headerLayout="@layout/nav_header_main"
41
        app:menu="@menu/drawer_menu" />
42
       
43
</androidx.drawerlayout.widget.DrawerLayout>
44

In the NavigationView XML widget, you can see that we added an android:layout_gravity attribute with the value start. This is used to position the drawer—you want the navigation drawer menu design to come out from the left or right (the start or end on platform versions that support layout direction). In our own case, the drawer will come out from the left. 

We also included an app:headerLayout attribute, which points to @layout/nav_header_main. This will add a View as a header of the navigation menu.

Here is my nav_header_main.xml layout resource file:

1
<?xml version="1.0" encoding="utf-8"?>
2
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3
    xmlns:app="http://schemas.android.com/apk/res-auto"
4
    android:layout_width="match_parent"
5
    android:layout_height="@dimen/nav_header_height"
6
    android:gravity="bottom"
7
    android:orientation="vertical"
8
    android:theme="@style/ThemeOverlay.AppCompat.Dark">
9
10
    <TextView
11
        android:layout_width="match_parent"
12
        android:layout_height="wrap_content"
13
        android:paddingTop="@dimen/nav_header_vertical_spacing"
14
        android:text="@string/nav_header_title"
15
        android:textAppearance="@style/TextAppearance.AppCompat.Body1" />
16
17
</LinearLayout>

To include the menu items for the navigation drawer, we can use the attribute app:menu with a value that points to a menu resource file. 

1
app:menu="@menu/drawer_menu" />

Here is the res/menu/drawer_menu.xml menu resource file:

1
<?xml version="1.0" encoding="utf-8"?>
2
<menu xmlns:android="http://schemas.android.com/apk/res/android"
3
    xmlns:tools="http://schemas.android.com/tools"
4
    tools:showIn="navigation_view">
5
6
    <group android:checkableBehavior="single">
7
        <item
8
            android:id="@+id/nav_home"
9
            android:icon="@drawable/home"
10
            android:title="@string/menu_home" />
11
        <item
12
            android:id="@+id/nav_gallery"
13
            android:icon="@drawable/person"
14
            android:title="@string/menu_gallery" />
15
        <item
16
            android:id="@+id/nav_slideshow"
17
            android:icon="@drawable/settings"
18
            android:title="@string/menu_slideshow" />
19
    </group>
20
</menu>

Here we have defined a Menu using the <menu> which serves as a container for menu items. An <item> creates a MenuItem, which represents a single item in a menu. It's also important to note that the ids of the menu items correspond to the ids of the matching fragment.

Note that when showing the navigation list items from a menu resource, we could use a ListView instead. But, by configuring the navigation drawer with a menu resource, we get the material design styling on the navigation drawer for free! If you used a ListView, you'd have to maintain the list and also style it to meet the recommended material design specs for the navigation drawer

Initialization of Components

Next, we are going to initialize instances of all our components. Initialization is going to happen inside onCreate() in MainActivity.kt.

The AppBarConfiguration object is used to manage the behavior of the navigation drawer button.

1
private lateinit var appBarConfiguration: AppBarConfiguration

First, we use the setSupportActionBar() method to set the toolbar as the app bar for the activity.

1
val toolbar: Toolbar = findViewById(R.id.toolbar)
2
        setSupportActionBar(toolbar)

Next, we set all fragments as top-level destinations, this means that they will remain in the back stack when navigating.

1
 // Passing each menu ID as a set of Ids because each

2
// menu should be considered as top level destinations.

3
        appBarConfiguration = AppBarConfiguration(setOf(
4
                R.id.home_menu, R.id.profile_menu, R.id.settings_menu), drawerLayout)

The method setupActionBarWithNavController automatically updates the title in the action bar when the destination changes.

1
setupActionBarWithNavController(navController, appBarConfiguration)

Set up the navigation drawer.

1
val navView: NavigationView = findViewById(R.id.nav_view)
2
val navController = findNavController(R.id.nav_host_fragment)
3
navView.setupWithNavController(navController)

Lastly, show the up button that appears at the top left of the app bar. This is done by integrating the navigation controller withe app bar using the onSupportNavigateUp method.

The final code for MainActivity.kt should look like this.

1
package com.example.navigationdrawer
2
3
// imports

4
5
class MainActivity : AppCompatActivity() {
6
7
    private lateinit var appBarConfiguration: AppBarConfiguration
8
9
    override fun onCreate(savedInstanceState: Bundle?) {
10
        super.onCreate(savedInstanceState)
11
        setContentView(R.layout.activity_main)
12
        val toolbar: Toolbar = findViewById(R.id.toolbar)
13
        setSupportActionBar(toolbar)
14
        ///

15
        val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout)
16
        val navView: NavigationView = findViewById(R.id.nav_view)
17
        val navController = findNavController(R.id.nav_host_fragment)
18
        // Passing each menu ID as a set of Ids because each

19
        // menu should be considered as top level destinations.

20
        appBarConfiguration = AppBarConfiguration(setOf(
21
                R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow), drawerLayout)
22
        setupActionBarWithNavController(navController, appBarConfiguration)
23
        navView.setupWithNavController(navController)
24
    }
25
26
27
    override fun onSupportNavigateUp(): Boolean {
28
        val navController = findNavController(R.id.nav_host_fragment)
29
        return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
30
    }
31
}
32

Testing the App

At this point, we can run the app!

navigation drawernavigation drawernavigation drawer

Bonus: Using Android Studio Templates

Now that you've learnt about the APIs involved to create a navigation drawer, I'll show you a shortcut that will make it faster next time. You can simply use a template instead of coding a navigation drawer Activity from scratch. 

Android Studio provides code templates that follow the Android design and development best practices. These existing code templates (available in Java and Kotlin) can help you quickly kick-start your project. One such template can be used to create a navigation drawer activity. 

I'll show you how to use this handy feature in Android Studio. 

For a new project, fire up Android Studio. 

Android Navigation Drawer Design Tutorial Create Android Project dialogAndroid Navigation Drawer Design Tutorial Create Android Project dialogAndroid Navigation Drawer Design Tutorial Create Android Project dialog

Enter the application name and click the Next button. 

You can leave the defaults as they're in the Target Android Devices dialog. Click the Next button again. 

Android Navigation Drawer Design Tutorial Add an Activity to Mobile dialogAndroid Navigation Drawer Design Tutorial Add an Activity to Mobile dialogAndroid Navigation Drawer Design Tutorial Add an Activity to Mobile dialog

In the Add an Activity to Mobile dialog, scroll down and select Navigation Drawer Activity. Click the Next button after that. 

Android Navigation Drawer Design Tutorial Configure Activity dialogAndroid Navigation Drawer Design Tutorial Configure Activity dialogAndroid Navigation Drawer Design Tutorial Configure Activity dialog

In the last dialog, you can rename the Activity name, layout name, or title if you want. Finally, click the Finish button to accept all configurations.

Android Studio has now helped us to create a project with a navigation drawer activity. Really cool! You're strongly advised to explore the code generated. 

You can use templates for an already existing Android Studio project too. Simply go to File > New > Activity > Navigation Drawer Activity.  

Android Navigation Drawer Design Tutorial Navigation from file menu too Navigation Drawer ActivityAndroid Navigation Drawer Design Tutorial Navigation from file menu too Navigation Drawer ActivityAndroid Navigation Drawer Design Tutorial Navigation from file menu too Navigation Drawer Activity

Top Android App Templates With Navigation Drawers From CodeCanyon

The templates that come included with Android Studio are good for simple layouts and making basic apps, but if you want to kick-start your app even further, you might consider some of the app templates available from Envato Market

They’re a huge time-saver for experienced developers, helping them to cut through the slog of creating an app from scratch and focus their talents instead on the unique and customised parts of creating a new app.

Here are just a small handful of the thousands of Android app templates available on CodeCanyon. If there's one that piques your interest, you can easily get started by making a purchase.

Grocery and Vegetable Delivery Android App with Admin Panel

If you or your client have a food delivery business, getting an app up and running is crucial. That's why you should consider this multi-store grocery service app template. It includes three templates with stunning layouts and Android hamburger menus. There's no limit to the categories you can add, and you can also use SMS and email order notifications.

Grocery and Vegetable Delivery Android App TemplateGrocery and Vegetable Delivery Android App TemplateGrocery and Vegetable Delivery Android App Template

Universal: Full Multi-Purpose Android App

Buying the Universal Android app template is just like downloading a Swiss Army knife. It can do it all, from WordPress and Facebook to Twitter and SoundCloud. In fact, there is a list of more than 15 content providers that this template supports. Users can access important information from the slick side menu design and easily make their way around their favorite sites.

Universal Multi Purpose Android App TemplateUniversal Multi Purpose Android App TemplateUniversal Multi Purpose Android App Template

MaterialX: Android Material Design UI Components 2.7

MaterialX is a recommended download for any app developer. It includes more than 315 unique UI components across more than 31 categories. Create stunning Android side menu designs, buttons, dialog boxes, and more from this single download. If you want a quick way to add some much-needed style to your new project, get this template.

MaterialX Android Material Design UI Components DownloadMaterialX Android Material Design UI Components DownloadMaterialX Android Material Design UI Components Download

Universal Android WebView App

Do you have content hosted online that you want to turn into a mobile experience? Then check out the Universal Android WebView App template. It was developed in Android Studio and supports phones and tablets running Android 4.1 and above. The Android navigation drawer menu design is completely customizable, as are other components. It also supports AdMob for monetization.

Universal Android WebView App TemplateUniversal Android WebView App TemplateUniversal Android WebView App Template

Android Wallpapers App

Here's a cool Android app template that's useful if you want to get your creative designs out into the world. The Android Wallpapers app supports static images, GIFs, and 4K photos. This template also includes useful features like:

  • pinch to zoom
  • push notifications
  • AdMob advertisement support
  • Android Studio code

Android Wallpapers App TemplateAndroid Wallpapers App TemplateAndroid Wallpapers App Template

Conclusion

In this tutorial, you learned how to create a navigation drawer menu design in Android from scratch, using Jetpack navigation. We also explored how easy and quick it is to use Android Studio templates to create a navigation drawer. 

I highly recommend checking out the official material design guidelines for navigation drawers to learn more about how to properly design and use navigation drawers in Android.   

To learn more about coding for Android, check out some of our other courses and tutorials here on Envato Tuts+!

This post has been updated with contributions from Nathan Umoh. Nathan is a staff writer for Envato Tuts+.

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.