Android NavigationView Using Kotlin With Example

In this article, we will learn about android NavigationView using Kotlin. We will go through various example that demonstrates how to use different attributes of NavigationView. For example,

In this article, we will get answer to questions like –

  • What is NavigationView?
  • Why should we consider NavigationView while designing ui for any app?
  • What are possibilities using NavigationView while designing ui? etc.

Let’s have a quick demo of things we want to cover in this tutorial –

Output

Tutorialwing Kotlin Android NavigationView Using Kotlin With Example

Getting Started

We can define android NavigationView widget as below –

NavigationView is standard navigation menu for application. User can navigate between different top level views of application using it.

If your app have some top level categories, navigationView can easily be used to provide a way to navigate between different categories. You may have seen some ecommerce android apps like flipkart, amazon, uber etc. Check the sample ui below –
Tutorialwing Kotlin Android NavigationView Using Kotlin Sample Application in Real Life

Now, how do we use NavigationView in android application ?

Creating New Project

At first, we will create an application.
So, follow steps below to create any android project in Kotlin –

Step Description
1. Open Android Studio (Ignore if already done).
2. Go to File => New => New Project. This will open a new window. Then, under Phone and Tablet section, select Empty Activity. Then, click Next.
3. In next screen, select project name as NavigationView. Then, fill other required details.
4. Then, clicking on Finish button creates new project.

Newbie in Android ?

Some very important concepts (Recommended to learn before you move ahead)

Before we move ahead, we need to setup for viewBinding to access Android NavigationView Using Kotlin file without using findViewById() method.

Setup ViewBinding

Add viewBinding true in app/build.gradle file.

 
 android { 
 	// OTHER CODE... 
 	buildFeatures { 
 		viewBinding true 
 	} 
 } 
 

Now, set content in activity using view binding.
Open MainActivity.kt file and write below code in it.

 
 class MainActivity : AppCompatActivity() { 
 	
 	private lateinit var binding: ActivityMainBinding 
 	
 	override fun onCreate(savedInstanceState: Bundle?) { 
 		super.onCreate(savedInstanceState) 
 		binding = ActivityMainBinding.inflate(layoutInflater) 
 		val view = binding.root 
 		setContentView(view) 
 	} 
 } 
 

Now, we can access view in Kotlin file without using findViewById() method.

Using NavigationView in Kotlin

Follow steps below to use NavigationView in newly created project –

  • Open res/values/strings.xml file. Then, add below code into it.
    <resources>
        <string name="app_name">NavigationView</string>
        <string name="menu_home">Home</string>
        <string name="menu_gallery">Gallery</string>
        <string name="menu_slideshow">Slideshow</string>
        <string name="gallery">Gallery</string>
        <string name="home">Home</string>
        <string name="slideshow">Slide Show</string>
        <string name="gallery_ui">Gallery UI selected!</string>
        <string name="home_ui">Home UI selected!</string>
        <string name="slideshow_ui">SlideShow UI selected!</string>
    </resources>
    
  • Inside res/values/themes.xml file, change parent theme of application to Theme.MaterialComponents.DayNight.NoActionBar as shown below –
        <style name="Theme.NavigationView" parent="Theme.MaterialComponents.DayNight.NoActionBar">
        // Other Code...
        </style>
    
  • Now, we need some drawable resources for our application. So, you can either download it or follow steps to get it –
    1. You can create new image files by visiting links – Add Vector Image in Android Using Vector Asset Studio or Add Image in Android Studio Using Image Asset Studio .
    2. Alternatively, you can get drawable resources by downloading source code.
  • Open app/build.gradle file. Then, add below code in it –

    implementation 'androidx.navigation:navigation-fragment-ktx:2.3.5'
    implementation 'androidx.navigation:navigation-ui-ktx:2.3.5'
    
  • Now, we need to add navigation file for our application. So, create new folder, navigation, inside main/res folder. Then, create new file, main_navigation.xml, in main/res/navigation folder. Then, add below code in it –
    <?xml version="1.0" encoding="utf-8"?>
    <navigation 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/navigation"
        app:startDestination="@+id/home_dest">
    
        <fragment
            android:id="@+id/home_dest"
            android:name="com.tutorialwing.navigationview.HomeFragment"
            android:label="@string/home"
            tools:layout="@layout/home_fragment">
            <action
                android:id="@+id/action_home_to_gallery"
                app:destination="@id/gallery_dest" />
            <action
                android:id="@+id/action_home_to_slideshow"
                app:destination="@id/slideshow_dest" />
        </fragment>
    
        <fragment
            android:id="@+id/gallery_dest"
            android:name="com.tutorialwing.navigationview.GalleryFragment"
            android:label="@string/gallery"
            tools:layout="@layout/gallery_fragment" />
    
        <fragment
            android:id="@+id/slideshow_dest"
            android:name="com.tutorialwing.navigationview.SlideShowFragment"
            android:label="@string/slideshow"
            tools:layout="@layout/slideshow_fragment" />
    
    </navigation>
    
  • Now, we need to create menu file for our navigationView. So, create new folder, menu, in main/res folder. Then, create new file, drawer_menu.xml, in main/res/menu folder. Then, add below code in it –

    <?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        tools:showIn="navigation_view">
    
        <group android:checkableBehavior="single">
            <item
                android:id="@+id/nav_home"
                android:icon="@drawable/ic_home"
                android:title="@string/menu_home" />
            <item
                android:id="@+id/nav_gallery"
                android:icon="@drawable/ic_gallery"
                android:title="@string/menu_gallery" />
            <item
                android:id="@+id/nav_slideshow"
                android:icon="@drawable/ic_slideshow"
                android:title="@string/menu_slideshow" />
        </group>
    
    </menu>
    
  • Till now, we have created menu and navigation for our application. In our application, we are going to show three fragments – 1. Home, 2. Gallery and 3. Slideshow . So, we need to create these fragments now. So, follow steps below to create it –

    1. Create First Fragment (HomeFragment)

      Create new xml file, home_fragment.xml, in res/layout folder. Then, add below code in it –

      <?xml version="1.0" encoding="utf-8"?>
      <androidx.constraintlayout.widget.ConstraintLayout 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="match_parent">
      
          <TextView
              android:id="@+id/label"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:textSize="18sp"
              android:textStyle="bold"
              app:layout_constraintBottom_toBottomOf="parent"
              app:layout_constraintEnd_toEndOf="parent"
              app:layout_constraintStart_toStartOf="parent"
              app:layout_constraintTop_toTopOf="parent" />
      
      </androidx.constraintlayout.widget.ConstraintLayout>
      

      Now, create new Kotlin file, HomeFragment.kt, in com.tutorialwing.navigationview package. Then, add below code in it –

      package com.tutorialwing.navigationview
      
      import android.os.Bundle
      import android.view.LayoutInflater
      import android.view.View
      import android.view.ViewGroup
      import androidx.fragment.app.Fragment
      import com.tutorialwing.navigationview.databinding.HomeFragmentBinding
      
      class HomeFragment : Fragment() {
      
      	private lateinit var binding: HomeFragmentBinding
      
      	override fun onCreateView(
      		inflater: LayoutInflater,
      		container: ViewGroup?,
      		savedInstanceState: Bundle?
      	): View {
      		binding = HomeFragmentBinding.inflate(layoutInflater)
      		return binding.root
      	}
      
      	override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
      		super.onViewCreated(view, savedInstanceState)
      
      		setupData()
      	}
      
      	private fun setupData() {
      		binding.label.text = getString(R.string.home_ui)
      	}
      }
      

      In HomeFragment UI, we are showing only text.

    2. Create Second Fragment (GalleryFragment)

      Create new xml file, gallery_fragment.xml, in res/layout folder. Then, add below code in it –

      <?xml version="1.0" encoding="utf-8"?>
      <androidx.constraintlayout.widget.ConstraintLayout 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="match_parent">
      
          <TextView
              android:id="@+id/label"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:textSize="18sp"
              android:textStyle="bold"
              app:layout_constraintBottom_toBottomOf="parent"
              app:layout_constraintEnd_toEndOf="parent"
              app:layout_constraintStart_toStartOf="parent"
              app:layout_constraintTop_toTopOf="parent" />
      
      </androidx.constraintlayout.widget.ConstraintLayout>
      

      Now, create new Kotlin file, GalleryFragment.kt, in com.tutorialwing.navigationview package. Then, add below code in it –

      package com.tutorialwing.navigationview
      
      import android.os.Bundle
      import android.view.LayoutInflater
      import android.view.View
      import android.view.ViewGroup
      import androidx.fragment.app.Fragment
      import com.tutorialwing.navigationview.databinding.GalleryFragmentBinding
      
      class GalleryFragment : Fragment() {
      
      	private lateinit var binding: GalleryFragmentBinding
      
      	override fun onCreateView(
      		inflater: LayoutInflater,
      		container: ViewGroup?,
      		savedInstanceState: Bundle?
      	): View {
      		binding = GalleryFragmentBinding.inflate(layoutInflater)
      		return binding.root
      	}
      
      	override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
      		super.onViewCreated(view, savedInstanceState)
      
      		setupData()
      	}
      
      	private fun setupData() {
      		binding.label.text = getString(R.string.gallery_ui)
      	}
      }
      

      Here, we are showing only text related to gallery ui only.

    3. Create Third Fragment (SlideShowFragment)

      Create new xml file, slideshow_fragment.xml, in res/layout folder. Then, add below code in it –

      <?xml version="1.0" encoding="utf-8"?>
      <androidx.constraintlayout.widget.ConstraintLayout 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="match_parent">
      
          <TextView
              android:id="@+id/label"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:textSize="18sp"
              android:textStyle="bold"
              app:layout_constraintBottom_toBottomOf="parent"
              app:layout_constraintEnd_toEndOf="parent"
              app:layout_constraintStart_toStartOf="parent"
              app:layout_constraintTop_toTopOf="parent" />
      
      </androidx.constraintlayout.widget.ConstraintLayout>
      

      Now, create new Kotlin file, SlideShowFragment.kt, in com.tutorialwing.navigationview package. Then, add below code in it –

      package com.tutorialwing.navigationview
      
      import android.os.Bundle
      import android.view.LayoutInflater
      import android.view.View
      import android.view.ViewGroup
      import androidx.fragment.app.Fragment
      import com.tutorialwing.navigationview.databinding.SlideshowFragmentBinding
      
      class SlideShowFragment : Fragment() {
      
      	private lateinit var binding: SlideshowFragmentBinding
      
      	override fun onCreateView(
      		inflater: LayoutInflater,
      		container: ViewGroup?,
      		savedInstanceState: Bundle?
      	): View {
      		binding = SlideshowFragmentBinding.inflate(layoutInflater)
      		return binding.root
      	}
      
      	override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
      		super.onViewCreated(view, savedInstanceState)
      
      		setupData()
      	}
      
      	private fun setupData() {
      		binding.label.text = getString(R.string.slideshow_ui)
      	}
      }
      

      Here, we set text to be shown in setupData method.

  • Open res/layout/activity_main.xml file. Then, add below code in it –
    <?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:context=".MainActivity">
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">
    
            <androidx.appcompat.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="@color/purple_500"
                android:theme="@style/ThemeOverlay.MaterialComponents.Dark.ActionBar" />
    
            <fragment
                android:id="@+id/nav_host_fragment"
                android:name="androidx.navigation.fragment.NavHostFragment"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:defaultNavHost="true"
                app:navGraph="@navigation/main_navigation" />
    
        </LinearLayout>
    
        <com.google.android.material.navigation.NavigationView
            android:id="@+id/nav_drawer"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:fitsSystemWindows="true"
            app:menu="@menu/drawer_menu">
    
        </com.google.android.material.navigation.NavigationView>
    
    </androidx.drawerlayout.widget.DrawerLayout>
    

    In xml file, we have used –

    1. NavigationView: Here, we have set menu using app:menu=”” attribute.
    2. fragment: This is being used as container for Fragment related to selected menu in navigationView.
    3. Toolbar: Sets actionBar for application.
  • Now, we will access these these widgets like navigationView, toolbar in Kotlin file MainActivity.kt and setup drawer in it. So, open Kotlin file, MainActivity.kt, and add below code in it –

    package com.tutorialwing.navigationview
    
    import android.os.Bundle
    import android.widget.Toast
    import androidx.appcompat.app.AppCompatActivity
    import androidx.core.view.GravityCompat
    import androidx.navigation.NavController
    import androidx.navigation.findNavController
    import androidx.navigation.ui.AppBarConfiguration
    import androidx.navigation.ui.navigateUp
    import androidx.navigation.ui.setupActionBarWithNavController
    import androidx.navigation.ui.setupWithNavController
    import com.tutorialwing.navigationview.databinding.ActivityMainBinding
    
    class MainActivity : AppCompatActivity() {
    
    	private lateinit var binding: ActivityMainBinding
    
    	private lateinit var appBarConfiguration: AppBarConfiguration
    	private lateinit var navController: NavController
    
    	override fun onCreate(savedInstanceState: Bundle?) {
    		super.onCreate(savedInstanceState)
    
    		binding = ActivityMainBinding.inflate(layoutInflater)
    		setContentView(binding.root)
    
    		setSupportActionBar(binding.toolbar)
    
    		navController = findNavController(R.id.nav_host_fragment)
    
    		appBarConfiguration = AppBarConfiguration(
    			setOf(R.id.home_dest),
    			binding.drawerLayout
    		)
    
    		setupActionBar(navController, appBarConfiguration)
    		setupNavigationMenu(navController)
    
    		setupClickListener()
    	}
    
    	private fun closeDrawer() {
    		binding.drawerLayout.closeDrawer(GravityCompat.START)
    	}
    
    	private fun setupActionBar(navController: NavController, appBarConfig: AppBarConfiguration) {
    		setupActionBarWithNavController(navController, appBarConfig)
    	}
    
    	private fun setupNavigationMenu(navController: NavController) {
    		binding.navDrawer.setupWithNavController(navController)
    	}
    
    	override fun onSupportNavigateUp(): Boolean {
    		return navController.navigateUp(appBarConfiguration)
    	}
    
    	private fun setupClickListener() {
    		// Set item click listener to perform action on menu item click.
    		binding.navDrawer.setNavigationItemSelectedListener { menuItem -> // Toggle the checked state of menuItem.
    			menuItem.isChecked = !menuItem.isChecked
    			when (menuItem.itemId) {
    				R.id.nav_gallery -> {
    					navController.navigate(R.id.action_home_to_gallery)
    				}
    				R.id.nav_slideshow -> {
    					navController.navigate(R.id.action_home_to_slideshow)
    				}
    			}
    			Toast.makeText(
    				applicationContext,
    				menuItem.title.toString() + " Selected",
    				Toast.LENGTH_SHORT
    			).show()
    			closeDrawer()
    			true
    		}
    	}
    }
    

    Here,

    1. At first, we have set toolbar as actionBar of the application.
    2. closeDrawer() : Call this method when you need to close drawer. Note that we have provided drawer gravity as a parameter. Use GravityCompat.START when we want to close left drawer, or Use GravityCompat.END when we want to close right drawer.
    3. setupActionBar() : Here, we have called setupActionBarWithNavController() method that binds actionBar with navController and updates title whenever there is destination change in app.
    4. setupNavigationMenu() : Code inside this method sets up navigationView to be used with navController.
    5. onSupportNavigateUp() : It enables user to navigate up if we have proper setup for parent in manifest file.
    6. setupClickListener() : Here, we have set click listener for menu item inside navigationView. Whenever any menu is clicked, callback methods are called that checks id of the selected menu. Once it matches with anyone mentioned inside when block, it navigates to respective destination. Then, a toast message is shown and drawer is closed.

Now, run the application. We will get output as below –
Tutorialwing Kotlin Android NavigationView Using Kotlin With Example

Set Custom View in NavigationView

Till now, we have learnt about how to set menu inside navigationView, do some action when any menu is selected from navigationView. Now, what if we want to show some other ui apart from menu. What if we want to show some image, name etc. in header of navigationView ? How can we do it ?

In this section, we will go through some basic steps to set custom view for android navigationView using Kotlin. Follow steps below to do it –

  • Now, we will show one fragment inside navigationView. So, let’s create one first.
    Create new xml file, drawer_fragment.xml, in res/layout folder. Then, add below code in it –

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout 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="match_parent">
    
        <TextView
            android:id="@+id/label"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="18sp"
            android:textStyle="bold"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    

    For sake of simplicity of this article, we are showing only textView inside navigationView. So, we have used only TextView in drawer_fragment. However, we have design ui of our choice in this page.

    We also need Kotlin file for this xml file. So, create new Kotlin file, DrawerFragment.kt, in com.tutorialwing.navigationview package. Then, add below code in it –

    package com.tutorialwing.navigationview
    
    import android.os.Bundle
    import android.view.LayoutInflater
    import android.view.View
    import android.view.ViewGroup
    import androidx.fragment.app.Fragment
    import com.tutorialwing.navigationview.databinding.DrawerFragmentBinding
    
    class DrawerFragment : Fragment() {
    
    	private lateinit var binding: DrawerFragmentBinding
    
    	override fun onCreateView(
    		inflater: LayoutInflater,
    		container: ViewGroup?,
    		savedInstanceState: Bundle?
    	): View {
    		binding = DrawerFragmentBinding.inflate(layoutInflater)
    		return binding.root
    	}
    
    	override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    		super.onViewCreated(view, savedInstanceState)
    
    		setupData()
    	}
    
    	private fun setupData() {
    		binding.label.text = "Left Drawer Custom UI"
    	}
    }
    

    Here, we have set text in textView with id label.

  • Now, open activity_main.xml file. Then, replace our existing NavigationView tag with below –

        <com.google.android.material.navigation.NavigationView
            android:id="@+id/nav_drawer"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:fitsSystemWindows="true"
            app:menu="@menu/drawer_menu">
    
            <androidx.fragment.app.FragmentContainerView
                android:id="@+id/left_drawer_container"
                android:name="com.tutorialwing.navigationview.DrawerFragment"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
    
        </com.google.android.material.navigation.NavigationView>
    

    Finally, code inside activity_main.xml file is –

    <?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:context=".MainActivity">
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">
    
            <androidx.appcompat.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="@color/purple_500"
                android:theme="@style/ThemeOverlay.MaterialComponents.Dark.ActionBar" />
    
            <fragment
                android:id="@+id/nav_host_fragment"
                android:name="androidx.navigation.fragment.NavHostFragment"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:defaultNavHost="true"
                app:navGraph="@navigation/main_navigation" />
    
        </LinearLayout>
    
        <com.google.android.material.navigation.NavigationView
            android:id="@+id/nav_drawer"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:fitsSystemWindows="true"
            app:menu="@menu/drawer_menu">
    
            <androidx.fragment.app.FragmentContainerView
                android:id="@+id/left_drawer_container"
                android:name="com.tutorialwing.navigationview.DrawerFragment"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
    
        </com.google.android.material.navigation.NavigationView>
    
    </androidx.drawerlayout.widget.DrawerLayout>
    
  • Now, run application. We will output as below –
    Tutorialwing Kotlin Android NavigationView Using Kotlin With Example

Show NavigationView From Right Side

Till now, we have show navigationDrawer that opens from left side. What if we want to open it from right side ? How can we do it ?

In our application, we are going to modify few things to open our current drawer from right side. So, follow steps below to do it –

  1. Open activity_main.xml file. Then, add android:layout_gravity=”end” to com.google.android.material.navigation.NavigationView as below –
        <com.google.android.material.navigation.NavigationView
            android:id="@+id/nav_drawer"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="end">
    
            <androidx.fragment.app.FragmentContainerView
                android:id="@+id/left_drawer_container"
                android:name="com.tutorialwing.navigationview.DrawerFragment"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
    
        </com.google.android.material.navigation.NavigationView>
    
  2. Now, open MainActivity.kt file. Then, write code to handle click event of hamburger icon as below –
    	override fun onOptionsItemSelected(item: MenuItem): Boolean {
    		if (item.itemId == android.R.id.home) {
    			toggle()
    		}
    		return super.onOptionsItemSelected(item)
    	}
    
    	private fun toggle() {
    		val direction = GravityCompat.END
    		val drawerLayout = binding.drawerLayout
    		if (drawerLayout.isDrawerVisible(direction)) {
    			drawerLayout.closeDrawer(direction)
    		} else {
    			drawerLayout.openDrawer(direction)
    		}
    	}
    

    Finally, code inside MainActivity.kt file is –

    package com.tutorialwing.navigationview
    
    import android.os.Bundle
    import android.view.MenuItem
    import androidx.appcompat.app.AppCompatActivity
    import androidx.core.view.GravityCompat
    import androidx.navigation.NavController
    import androidx.navigation.findNavController
    import androidx.navigation.ui.AppBarConfiguration
    import androidx.navigation.ui.setupActionBarWithNavController
    import androidx.navigation.ui.setupWithNavController
    import com.tutorialwing.navigationview.databinding.ActivityMainBinding
    
    class MainActivity : AppCompatActivity() {
    
    	private lateinit var binding: ActivityMainBinding
    
    	private lateinit var appBarConfiguration: AppBarConfiguration
    	private lateinit var navController: NavController
    
    	override fun onCreate(savedInstanceState: Bundle?) {
    		super.onCreate(savedInstanceState)
    
    		binding = ActivityMainBinding.inflate(layoutInflater)
    		setContentView(binding.root)
    
    		setSupportActionBar(binding.toolbar)
    
    		navController = findNavController(R.id.nav_host_fragment)
    
    		appBarConfiguration = AppBarConfiguration(
    			setOf(R.id.home_dest),
    			binding.drawerLayout
    		)
    
    		setupActionBar(navController, appBarConfiguration)
    		setupNavigationMenu(navController)
    	}
    
    	private fun setupActionBar(navController: NavController, appBarConfig: AppBarConfiguration) {
    		setupActionBarWithNavController(navController, appBarConfig)
    	}
    
    	private fun setupNavigationMenu(navController: NavController) {
    		binding.navDrawer.setupWithNavController(navController)
    	}
    
    	override fun onOptionsItemSelected(item: MenuItem): Boolean {
    		if (item.itemId == android.R.id.home) {
    			toggle()
    		}
    		return super.onOptionsItemSelected(item)
    	}
    
    	private fun toggle() {
    		val direction = GravityCompat.END
    		val drawerLayout = binding.drawerLayout
    		if (drawerLayout.isDrawerVisible(direction)) {
    			drawerLayout.closeDrawer(direction)
    		} else {
    			drawerLayout.openDrawer(direction)
    		}
    	}
    }
    
  3. Now, run application. We will get output as below –
    Tutorialwing NavigationView Open Drawer from right side of the screen example

    That’s how we open android navigationView using Kotlin from right side of the screen.

Different Attributes of NavigationView in XML

Now, we will see how to use different attributes of Android NavigationView using Kotlin to customise it –

Set Id of NavigationView

Many a time, we need id of View to access it in kotlin file or create ui relative to that view in xml file. So, we can set id of NavigationView using android:id attribute like below –

    <com.google.android.material.navigation.NavigationView
        android:id="@+id/navigationView_ID"
        />

Here, we have set id of NavigationView as navigationView_ID using android:id=”” attribute. So, if we need to reference this NavigationView, we need to use this id – navigationView_ID.

Set Width of NavigationView

We use android:layout_width=”” attribute to set width of NavigationView.
We can do it as below –

    <com.google.android.material.navigation.NavigationView
        android:id="@+id/navigationView_ID"
        android:layout_width="wrap_content"
        />

Width can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value (like 20dp, 30dp etc.).

Set Height of NavigationView

We use android:layout_height=”” attribute to set height of NavigationView.
We can do it as below –

    <com.google.android.material.navigation.NavigationView
        android:id="@+id/navigationView_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

Height can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value.

Set Padding of NavigationView

We use android:padding=”” attribute to set padding of NavigationView.
We can do it as below –

    <com.google.android.material.navigation.NavigationView
        android:id="@+id/navigationView_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        />

Here, we have set padding of 10dp in NavigationView using android:padding=”” attribute.

Set Margin of NavigationView

We use android:layout_margin=”” attribute to set margin of NavigationView.
We can do it as below –

    <com.google.android.material.navigation.NavigationView
        android:id="@+id/navigationView_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        />

Here, we have set margin of 10dp in NavigationView using android:layout_margin=”” attribute.

Set Background of NavigationView

We use android:background=”” attribute to set background of NavigationView.
We can do it as below –

    <com.google.android.material.navigation.NavigationView
        android:id="@+id/navigationView_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#ff0000"
        />

Here, we have set background of color #ff0000 in NavigationView using android:background=”” attribute.

Set Visibility of NavigationView

We use android:visibility=”” attribute to set visibility of NavigationView.
We can do it as below –

    <com.google.android.material.navigation.NavigationView
        android:id="@+id/navigationView_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="gone"
        />

Here, we have set visibility of NavigationView using android:visibility=”” attribute. Visibility can be of three types – gone, visible and invisible

Till now, we have see how to use android NavigationView using Kotlin. We have also gone through different attributes of NavigationView to perform certain task.

We have seen different attributes of NavigationView and how to use it. If you wish to visit post to learn more about it

Thus, we have seen what is NavigationView, how can we use android NavigationView using Kotlin With Example? etc. We also went through different attributes of android NavigationView.

Leave a Reply