USING THE ANDROID NAVIGATION DRAWER IN KOTLIN

Ezichi Amarachi
2 min readJan 28, 2020

--

A wise woman once said and i rephrase “writing is one of the most effective ways to learn…”. On this note, let’s learn about the Android Navigation Drawer.

The navigation drawer is a component of the android material design library. It’s an overlay page which slides out from the left edge of an app. From the navigation drawer, the user can easily navigate to many other screens and functionalities in the app and this makes it an important UI component. A good example of an app that makes use of the navigation drawer is the Google’s Gmail app.

Ok, enough talking. Let’s get right down to coding.

The first step to using the navigation drawer in our app is to include the material design library in the ‘dependencies’ block in our app’s build.gradle file:

In our activity_main.xml file, we’ll make the DrawerLayout tag our root layout. Like this:

Now, we’ll create a new menu resource file. Navigate to app>src>main>res, right-click on res and select new>android resource file. We’ll give the file a value of menu and name it ‘drawer_list’. Let’s also create another android resource file, the value will be layout this time and we’ll name it ‘nav_header’.

Next, we’ll add the NavigationView widget which is part of the support design library to our activity_main.xml file, inside the DrawerLayout root layout. We’ll first add the library to the ‘dependencies’ block:

Then, we’ll add the NavigationView widget:

In the NavigationView, we’ll set the app:menu and app:headerLayout attributes to use the menu and layout files we created, respectively.

Now, we’ll edit the drawer_list.xml to display some items

and edit the nav_header.xml to add an image that’ll serve as the drawer header:

Now, let’s write some kotlin code.

Let’s open the MainActivity.kt file and write down the following blocks of code. Read through the comments to understand the function of each block.

Now, we have a Drawer which shows up when we slide from the left edge of the screen and displays a toast message when an item is clicked. Great!. But when the hamburger icon is clicked, nothing happens. Well, let’s fix that too. We’ll add the following code into the MainActivity : AppCompatActivity()class:

…and we have a functional drawer!.

Our app now looks like this

Great job guys!!. Now, you can go find someone with whom you can share your success. If this content was helpful to you, don’t forget to leave a clap.

Happy coding :)

--

--

Ezichi Amarachi

Android Engineer with 5 years of experience in Native Android Development. Open for EU/UK based roles with relocation.