Navigation Drawer in Kotlin Android - Android Hire
Android Phones

Navigation Drawer in Kotlin Android

Jayant dhingra
So What is Kotlin ?

Kotlin is a cross-platform, statically typed, general-purpose programming language with type inference. Kotlin is designed to interoperate fully with Java, and the JVM version of its standard library depends on the Java Class Library

Also it is the official language for android.

In this post, we will make a navigation drawer in android. The navigation drawer is a panel that slides out from the left of the screen and contains a range of options available for selection by the user, typically intended to facilitate navigation to some other part of the application.

Here is an Example.

Navigation Drawer in Kotlin Android CODE

STEP 0

Create a New Android Project with Kotlin support.

STEP 1

We need to change our style because we have to implement our own toolbar. Add the below style open your styles.xml file and add this 1 new style. You can find styles.xml in- app => res => values => styles.xml

STEP 2

To make navigation Drawer we don't need any dependency but to make it look beautiful we will use Material UI dependency.

//Add in Build.gradle(app)
//Change dependency according to latest version.

dependencies {
   implementation 'com.google.android.material:material:1.1.0'
}

STEP 3

To create a navigation drawer we have to create these things

  • 2 layout files => content_main.xml and nav_header.xml
  • 1 menu file => nav_menu.xml

nav_header.xml

This is the header file which is shown below




    

    

    

content_main.xml

We can write the code for content_main.xml in activity_main.xml also but we make a separate layout to keep the activity_main.xml clean. So in content_main.xml, we will just have a FrameLayout.




    

        

            
               
            
        

    


    
        
    

AppBarLayout is a ViewGroup, most commonly used to wrap a Toolbar, that provides many of the Material Design features. Inside Toolbar we can design our action bar now as we want.

In activity_main.xml




    

    

As you can see, the layouts that will contain our navigation drawer must have a DrawerLayout as a parent view. our other UI design codes will be inside this. Here include tag is used to grab all the views from another layout resource file.

Thats why, to make our codes clean, we'll put all other designs including custom action bar in our content_main.xml file.

And at the bottom of our DrawerLayout, we used the NavigationView which actually generates the navigation drawer. For using this view we implemented the library before called com.google.android.material:material:1.1.0

The NavigationView mainly contains two things, one is the headerLayout for designing the header section of our Navigation Drawer, and the other is the menu which will display the listed options in our Navigation Drawer.

For designing our header layout we created a layout resource file "nav_header.xml" and a menu resource file "nav_menu.xml" for creating the list options.

READ MORE: How to Connect Firebase to your Android Project [Step by Step Guide]

STEP 4

Now we will create our menu file i.e. – nav_menu.xml




    
        
        
        
    


    
        
            
            
        
    
If you look at the above code, I created a menu using menu, item, and group.
menu which is the root element and it can have sub child's/sub elements like item and group.

This is menu items .

The important thing here is android: icon, here you should use vector icons. To add vector icons, right-click on app => New => Vector Asset

STEP 5

Now we will implement MainActivity.kt

package com.jayant.navigationdrawer

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.MenuItem
import android.widget.Toast
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.appcompat.widget.Toolbar
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import com.google.android.material.navigation.NavigationView

class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {


    lateinit var toolbar: Toolbar
    lateinit var drawerLayout: DrawerLayout
    lateinit var navView: NavigationView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        toolbar = findViewById(R.id.toolbar)
        setSupportActionBar(toolbar)

        drawerLayout = findViewById(R.id.drawer_layout)
        navView = findViewById(R.id.nav_view)

        val toggle = ActionBarDrawerToggle(
            this, drawerLayout, toolbar, 0, 0
        )
        drawerLayout.addDrawerListener(toggle)
        toggle.syncState()
        navView.setNavigationItemSelectedListener(this)
    }

    override fun onNavigationItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.nav_profile -> {
                Toast.makeText(this, "Profile clicked", Toast.LENGTH_SHORT).show()
            }
            R.id.nav_messages -> {
                Toast.makeText(this, "Messages clicked", Toast.LENGTH_SHORT).show()
            }
            R.id.nav_friends -> {
                Toast.makeText(this, "Friends clicked", Toast.LENGTH_SHORT).show()
            }
            R.id.nav_update -> {
                Toast.makeText(this, "Update clicked", Toast.LENGTH_SHORT).show()
            }
            R.id.nav_logout -> {
                Toast.makeText(this, "Sign out clicked", Toast.LENGTH_SHORT).show()
            }
        }
        drawerLayout.closeDrawer(GravityCompat.START)
        return true
    }
}

Let me make the code little clear now.

ActionBarDrawerToggle is for displaying an drawer indicator in the appbar which needs 5 arguments.

  1. Current Activity context
  2. DrawerLayout variable
  3. Toolbar variable
  4. Drawer open description message via Resource string
  5. Drawer close description message via Resource string

Then we added the ActionBarDrawerToggle into our DrawerLayout view and synced it. Now it will display a drawer indicator in our app bar.

Also, we will need to detect user's interaction with the listed options in the Navigation Drawer. for this, we'll need to implement a listener into our class using NavigationView.OnNavigationItemSelectedListener, this will allow us to override onNavigationItemSelected(item: MenuItem) function. Inside this function, we can set what will happen after clicking which option.

Now Run the application and see the result

That's all Folks!!

Jayant dhingra's profile picture

Jayant dhingra

As an enthusiast of stock markets and a skilled developer specializing in Android and augmented reality technologies, I am constantly driven to experiment with code.

Related Posts

7 Top Samsung Galaxy Ring Alternatives for 2025

7 Top Samsung Galaxy Ring Alternatives for 2025

Tired of waiting for the Samsung Galaxy Ring to hit the market? You’re not alone. While the buzz around Samsung’s smart ring continues, a plethora of impressive alternatives is already available. These devices deliver advanced health tracking, stylish designs, and unique features that cater to various lifestyles. The current lineup of smart rings caters to […]

What Is Quiet Mode on Instagram and How to Activate It

What Is Quiet Mode on Instagram and How to Activate It

Ever wondered what Quiet Mode on Instagram is all about? This simple yet powerful Instagram feature helps you take a break from the constant buzz of notifications and focus on what truly matters. Whether you’re striving for better work-life balance, dedicating time to studying, or simply trying to disconnect from social media distractions, Quiet Mode […]

How to Make a Bed in Minecraft (Step-by-Step Guide)

How to Make a Bed in Minecraft (Step-by-Step Guide)

A bed in Minecraft is very important. It lets you skip the night and set your spawn point, so if you die, you will return to your bed instead of the original world spawn. This guide will show you how to gather materials, craft a bed, and set your spawn point. We’ll also show you how to customize your bed, build bunk […]

10 Best MMORPG Games For Android

10 Best MMORPG Games For Android

Not too long ago, MMORPG games and powerful gaming consoles were mostly exclusive to PCs. They required high-end graphics and systems to deliver their immersive gameplay. But times have changed. With the rise of gaming-oriented smartphones, you can now enjoy PC-like gaming experiences on your Android device. Thanks to these technological advancements and faster internet […]

Roblox: Fruit Battlegrounds codes (January 2025)

Roblox: Fruit Battlegrounds codes (January 2025)

Fruit Battlegrounds codes are all about getting more gems and help you to shoot up your rank in this One Piece anime-inspired game. This Fruit Battlegrounds was made by Popo developer. It is an action-packed game where players battle it out using unique fruit-based abilities. With constant updates, new fruits, and exciting challenges, it’s a fruity frenzy you won’t […]

Roblox: Ultimate Football Codes (January 2025)

Roblox: Ultimate Football Codes (January 2025)

Want to get some extra items for Ultimate Football in Roblox? You’ve come to the right place! Here’s the latest list of codes to help you score touchdowns and look stylish on the field. These codes offer free rewards such as coins and cosmetics to enhance your gameplay. What are Ultimate Football Codes? Ultimate Football […]

Roblox: Da Hood Codes (January 2025)

Roblox: Da Hood Codes (January 2025)

Are you a fan of Roblox games, in this article we will look at the Roblox Da Hood Codes for December 2024 that will help you unlock exclusive items, improve your gameplay and dominate the streets of Da Hood. You can feel that the game is inspired by the Grand Theft Auto series and there […]