Navigation Drawer in Kotlin Android

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

Navigation Drawer in Kotlin Android 1

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 2

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

<style name="AppTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>

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

Navigation Drawer in Kotlin Android 3
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:background="#4CAF50"
        android:orientation="vertical"
        android:gravity="bottom"
        android:paddingLeft="15dp"
        android:paddingBottom="15dp">

    <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:srcCompat="@mipmap/ic_launcher"
            android:id="@+id/imageView"
            android:layout_marginBottom="15dp"/>

    <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Title"
            android:textColor="#FFFFFF"
            android:textStyle="bold"/>

    <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="This is our navigation drawer"
            android:textColor="#FFFFFF"/>

</LinearLayout>

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.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:app="http://schemas.android.com/apk/res-auto"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <com.google.android.material.appbar.AppBarLayout
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <androidx.appcompat.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="?attr/colorPrimary"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light">

            <FrameLayout
                    android:id = "@+id/main_fragment"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                   >
               
            </LinearLayout>
        </androidx.appcompat.widget.Toolbar>

    </com.google.android.material.appbar.AppBarLayout>


    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">
        <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="This is my content area."/>
    </LinearLayout>

</LinearLayout>

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

<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        tools:openDrawer="start">

    <include
            layout="@layout/content_main"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

    <com.google.android.material.navigation.NavigationView
            android:id="@+id/nav_view"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:fitsSystemWindows="true"
            app:headerLayout="@layout/nav_header"
            app:menu="@menu/nav_menu"/>

</androidx.drawerlayout.widget.DrawerLayout>

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

Navigation Drawer in Kotlin Android 4
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <group>
        <item
                android:id="@+id/nav_profile"
                android:icon="@drawable/ic_profile"
                android:title="Profile"/>
        <item
                android:id="@+id/nav_messages"
                android:icon="@drawable/ic_messages"
                android:title="Messages"/>
        <item
                android:id="@+id/nav_friends"
                android:icon="@drawable/ic_friends"
                android:title="Friends"/>
    </group>


    <item android:title="Account Settings">
        <menu>
            <item
                    android:id="@+id/nav_update"
                    android:icon="@drawable/ic_update"
                    android:title="Update Profile"/>
            <item
                    android:id="@+id/nav_logout"
                    android:icon="@drawable/ic_signout"
                    android:title="Sign Out"/>
        </menu>
    </item>
</menu>
If you look at the above code, I created a menu using menuitem, 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

Navigation Drawer in Kotlin Android 5

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
Jayant
I am an android and augmented reality developer and stock market enthusiast who loves to play with code. Come let's connect Gitter - @jayant1441 Github - github.com/jayant1441

Latest news

Everything about Android Latest Version

When Google launched the Google Android-powered Nexus One telephone on January 5, 2010, Jobs, Apple Chief executive officer responded to that development in a...

Use of “Services.dart” Package in the Flutter

We often come at a point where we need some flexibility, in our app UI. so in this blog, I want to share two...

One Plus 8T: All you need to know!

One Plus unveiled its 2020 flagship in a virtual event named One Plus 8T. In this post we would go through its specifications ,...

Twitter may launch new features to simplify direct messages.

Twitter is said to be working on a couple of new features that could make it easier to manage direct messages and retweeting. The...

Related news

Everything about Android Latest Version

When Google launched the Google Android-powered Nexus One telephone on January 5, 2010, Jobs, Apple Chief executive officer responded to that development in a...

Use of “Services.dart” Package in the Flutter

We often come at a point where we need some flexibility, in our app UI. so in this blog, I want to share two...

One Plus 8T: All you need to know!

One Plus unveiled its 2020 flagship in a virtual event named One Plus 8T. In this post we would go through its specifications ,...

Twitter may launch new features to simplify direct messages.

Twitter is said to be working on a couple of new features that could make it easier to manage direct messages and retweeting. The...