NavigationView in Android with Java

Introduction

 
In this article, we will learn about NavigationView in Android with Java Programming Language.
 

NavigationView in Android

 
NavigationView is a simple way to access a Menu tool navigation chart. This is the most widely used method to incorporate content navigation drawers in combination with the DrawerLayout. Navigation drawers are modal elevated dialogues and are used to display in-app navigation links coming from the left/start side. NavigationView is a scrollable view that allows a menu feature as a vertical column.
 

Navigation Drawer in Android 

 
The most common usage for NavigationView is to add navigation drawers, this section will teach you how to use NavigationView for that purpose. 
 

How does NavigationView work in Android?

 
NavigationView in Android is placed in the Navigation Drawer. When we work with Navigation View we see three small lines on the left side of the toolbar on the home screen of the Android Application, when we click on it a navigation drawer opens from the left side of the screen as shown in the below image.
 
navigation view
 
As we can see in the image there are two screen images. In the first screen, there is an Activity that shows the message that "Message is Selected" and the toolbar" NavigationViewExample" on the left side of the toolbar with three lines. In the second screen, we click these three lines and our navigation view opens.
 
Now we will see the example of Navigation View in Android Studio step by step.
 
Step 1
 
First, we will create an Android Studio project named Example. Android Studio will create two files in the project MainActivity.java and activity_main.xml.
 
Step 2
 
Before starting with NavigationView we have to add the dependency that is used for NavigationView in our build.gradle code file of the application. Here is our build.gradle file.
  1. apply plugin: 'com.android.application'  
  2.   
  3. android {  
  4.     compileSdkVersion 29  
  5.   
  6.     defaultConfig {  
  7.         applicationId "manigautam.apps.navigationviewexample"  
  8.         minSdkVersion 21  
  9.         targetSdkVersion 29  
  10.         versionCode 1  
  11.         versionName "1.0"  
  12.   
  13.         testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"  
  14.     }  
  15.   
  16.     buildTypes {  
  17.         release {  
  18.             minifyEnabled false  
  19.             proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'  
  20.         }  
  21.     }  
  22. }  
  23.   
  24. dependencies {  
  25.     implementation fileTree(dir: "libs", include: ["*.jar"])  
  26.     implementation 'androidx.appcompat:appcompat:1.2.0'  
  27.     implementation 'androidx.constraintlayout:constraintlayout:1.1.3'  
  28.     implementation 'com.google.android.material:material:1.2.0'  
  29.     testImplementation 'junit:junit:4.12'  
  30.     androidTestImplementation 'androidx.test.ext:junit:1.1.1'  
  31.     androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'  
  32.   
We add the material dependency in build.gradle file of the Android application which is used for material design, and NavigationView is also a part of it. After adding the RecyclerView dependency in our project sync the project.
 
Step 3 
 
After the successful sync of the project, we will change the theme according to our NavigationView. So, we will create a style for our project in the styles.xml file. Here is the code of styles.xml file.
  1. <resources>  
  2.     <!-- Base application theme. -->  
  3.     <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">  
  4.         <!-- Customize your theme here. -->  
  5.         <item name="colorPrimary">@color/colorPrimary</item>  
  6.         <item name="colorPrimaryDark">@color/colorPrimaryDark</item>  
  7.         <item name="colorAccent">@color/colorAccent</item>  
  8.     </style>  
  9.   
  10.         <style name="AppTheme.NoActionBar">  
  11.             <item name="windowActionBar">false</item>  
  12.             <item name="windowNoTitle">true</item>  
  13.             <item name="android:statusBarColor">@android:color/transparent</item>  
  14.   
  15.         </style>  
  16.   
  17. </resources> 
Step 4
 
We will change the theme of the project in our manifest.xml file. So here is the code example of manifest.xml file of the project.
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="manigautam.apps.navigationviewexample">  
  4.   
  5.     <application  
  6.         android:allowBackup="true"  
  7.         android:icon="@mipmap/ic_launcher"  
  8.         android:label="@string/app_name"  
  9.         android:roundIcon="@mipmap/ic_launcher_round"  
  10.         android:supportsRtl="true"  
  11.         android:theme="@style/AppTheme">  
  12.         <activity android:name=".MainActivity"  
  13.           android:theme="@style/AppTheme.NoActionBar">  
  14.   
  15.             <intent-filter>  
  16.                 <action android:name="android.intent.action.MAIN" />  
  17.   
  18.                 <category android:name="android.intent.category.LAUNCHER" />  
  19.             </intent-filter>  
  20.         </activity>  
  21.     </application>  
  22.   
  23. </manifest> 
Step 5
 
Now we will create a new layout file named nav_header.xml, which will be the header of the NavigationView. So, here is the code of nav_header.xml file.
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="176dp"  
  5.     android:background="@color/colorAccent"  
  6.     android:gravity="bottom"  
  7.     android:orientation="vertical"  
  8.     android:padding="16dp"  
  9.     android:theme="@style/ThemeOverlay.AppCompat.Dark">  
  10.   
  11.     <ImageView  
  12.         android:layout_width="wrap_content"  
  13.         android:layout_height="wrap_content"  
  14.         android:src="@mipmap/ic_launcher_round" />  
  15.   
  16.     <TextView  
  17.         android:layout_width="wrap_content"  
  18.         android:layout_height="wrap_content"  
  19.         android:padding="8dp"  
  20.         android:text="User Name"  
  21.         android:textAppearance="@style/TextAppearance.AppCompat.Body1" />  
  22.   
  23.     <TextView  
  24.         android:layout_width="wrap_content"  
  25.         android:layout_height="wrap_content"  
  26.         android:text="Usermail@gail.com" />  
  27.   
  28. </LinearLayout> 
Step 6
 
After creating the NavigationView header we will create a menu file named drawer_menu for adding the menu items for the NavigationView. Here is the code of the drawer_menu.xml 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_message"  
  9.             android:icon="@drawable/ic_message"  
  10.             android:title="Message" />  
  11.         <item  
  12.             android:id="@+id/nav_chat"  
  13.             android:icon="@drawable/ic_chat"  
  14.             android:title="Chat" />  
  15.         <item  
  16.             android:id="@+id/nav_profile"  
  17.             android:icon="@drawable/ic_profile"  
  18.             android:title="Profile" />  
  19.   
  20.     </group>  
  21.     <item android:title="Commnuicate">  
  22.         <menu>  
  23.             <item  
  24.                 android:id="@+id/nav_share"  
  25.                 android:icon="@drawable/ic_share"  
  26.                 android:title="Share" />  
  27.   
  28.             <item  
  29.                 android:id="@+id/nav_send"  
  30.                 android:icon="@drawable/ic_send"  
  31.                 android:title="Send" />  
  32.         </menu>  
  33.     </item>  
  34. </menu> 
Here we make two groups in our menu file. In the first group, we create three items: message, chat, and profile. In the second group, we create two items, name share and send. In every item, we add title, id, and an icon for every item. For icons we add some icons in our drawable file, and we also can use images as the icons, for this, we have to add the images in our drawable file of the project.
 
Step 7
 
Now we will create the Fragment Java classes and layouts for these fragments for every item which we add in our menu file. So when we select any item from this list the Fragment of this item will be open, and as the home screen, we will open a Fragment named "Message". So here is the code of these Fragments.
 
Here is the layout file named fragment_message.xml file for the Message item. 
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:background="@android:color/holo_orange_dark">  
  6.   
  7.     <TextView  
  8.         android:layout_width="wrap_content"  
  9.         android:layout_height="wrap_content"  
  10.         android:layout_centerInParent="true"  
  11.         android:text="Message is Selected"  
  12.         android:textSize="30sp" />  
  13. </RelativeLayout> 
In this fragment layout file, we will show a message through the TextView that "Message is Selected". Now let's see the Fragment Java Class named MessageFragment.java.
  1. import android.os.Bundle;  
  2. import android.view.LayoutInflater;  
  3. import android.view.View;  
  4. import android.view.ViewGroup;  
  5.   
  6. import androidx.annotation.NonNull;  
  7. import androidx.annotation.Nullable;  
  8. import androidx.fragment.app.Fragment;  
  9.   
  10. public class MessageFragement extends Fragment {  
  11.   
  12.     @Nullable  
  13.     @Override  
  14.     public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {  
  15.         return inflater.inflate(R.layout.fragment_message, container, false);  
  16.     }  
Now, here is the layout file named fragment_chat.xml file for the Chat item.
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:background="@android:color/holo_blue_dark">  
  6.   
  7.     <TextView  
  8.         android:layout_width="wrap_content"  
  9.         android:layout_height="wrap_content"  
  10.         android:layout_centerInParent="true"  
  11.         android:text="Chat is Selected"  
  12.         android:textSize="30sp" />  
  13.   
  14. </RelativeLayout> 
In this fragment layout file, we will show a message through the TextView that "Chat is Selected". Now let's see the Fragment Java Class named ChatFragment.java.
  1. import android.os.Bundle;    
  2. import android.view.LayoutInflater;    
  3. import android.view.View;    
  4. import android.view.ViewGroup;    
  5.     
  6. import androidx.annotation.NonNull;    
  7. import androidx.annotation.Nullable;    
  8. import androidx.fragment.app.Fragment;    
  9.     
  10. public class ChatFragment extends Fragment {    
  11.     @Nullable    
  12.     @Override    
  13.     public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {    
  14.         return inflater.inflate(R.layout.fragemnt_chat,container,false);    
  15.     }    
  16. }    
Now, here is the layout file named fragment_profile.xml file for the Profile item. 
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:background="@android:color/holo_purple">  
  6.   
  7.     <TextView  
  8.         android:layout_width="wrap_content"  
  9.         android:layout_height="wrap_content"  
  10.         android:text="Profile is Selected"  
  11.         android:textSize="30sp"  
  12.         android:layout_centerInParent="true"  
  13.         />  
  14.   
  15. </RelativeLayout> 
In this fragment layout file, we will show a message through the TextView that "Profile is Selected". Now let's see the Fragment Java Class named ProfileFragment.java.
  1. import android.os.Bundle;  
  2. import android.view.LayoutInflater;  
  3. import android.view.View;  
  4. import android.view.ViewGroup;  
  5.   
  6. import androidx.annotation.NonNull;  
  7. import androidx.annotation.Nullable;  
  8. import androidx.fragment.app.Fragment;  
  9.   
  10. public class ProfileFragment extends Fragment {  
  11.     @Nullable  
  12.     @Override  
  13.     public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {  
  14.         return inflater.inflate(R.layout.fragment_profile,container,false);  
  15.     }  
  16. }
Now, here is the layout file named fragment_share.xml file for the Share item.
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:background="@android:color/white">  
  6.   
  7.     <TextView  
  8.         android:layout_width="wrap_content"  
  9.         android:layout_height="wrap_content"  
  10.         android:text="Share"  
  11.         android:textSize="30sp"  
  12.         android:layout_centerInParent="true"  
  13.         />  
  14.   
  15. </RelativeLayout> 
In this fragment layout file, we will show a message. "Share,"  through the TextView. Now let's see the Fragment Java Class named ShareFragment.java.
  1. import android.os.Bundle;  
  2. import android.view.LayoutInflater;  
  3. import android.view.View;  
  4. import android.view.ViewGroup;  
  5.   
  6. import androidx.annotation.NonNull;  
  7. import androidx.annotation.Nullable;  
  8. import androidx.fragment.app.Fragment;  
  9.   
  10. public class ShareFragment extends Fragment {  
  11.         @Nullable  
  12.         @Override  
  13.         public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {  
  14.             return inflater.inflate(R.layout.fragment_share,container,false);  
  15.         }  
Now, here is the layout file named fragment_send.xml file for the Send item.
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:background="@android:color/holo_orange_light">  
  6.   
  7.     <TextView  
  8.         android:layout_width="wrap_content"  
  9.         android:layout_height="wrap_content"  
  10.         android:text="Send"  
  11.         android:textSize="30sp"  
  12.         android:layout_centerInParent="true"  
  13.         />  
  14.   
  15. </RelativeLayout> 
In this fragment layout file, we will show a message, "Send," through the TextView. Now let's see the Fragment Java Class named SendFragment.java.
  1. import android.os.Bundle;  
  2. import android.view.LayoutInflater;  
  3. import android.view.View;  
  4. import android.view.ViewGroup;  
  5.   
  6. import androidx.annotation.NonNull;  
  7. import androidx.annotation.Nullable;  
  8. import androidx.fragment.app.Fragment;  
  9.   
  10. public class SendFragment extends Fragment {  
  11.   
  12.     @Nullable  
  13.     @Override  
  14.     public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,  
  15.                              @Nullable Bundle savedInstanceState) {  
  16.         return inflater.inflate(R.layout.fragment_send, container, false);  
  17.     }  
So, these are the fragment layouts and the Java Fragment files for all the items, which we have created in our menu file.
 
Step 8 
 
Now, we will create our NavigationView in our ativity_main.xml file. So, here is the code of activity_main.xml file.
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://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:context=".MainActivity"  
  10.     tools:openDrawer="start">  
  11.   
  12.     <LinearLayout  
  13.         android:layout_width="match_parent"  
  14.         android:layout_height="match_parent"  
  15.         android:orientation="vertical">  
  16.   
  17.         <FrameLayout  
  18.             android:id="@+id/fragment_container"  
  19.             android:layout_width="match_parent"  
  20.             android:layout_height="match_parent" />  
  21.   
  22.         <androidx.appcompat.widget.Toolbar  
  23.             android:id="@+id/toolbar"  
  24.             android:layout_width="match_parent"  
  25.             android:layout_height="?attr/actionBarSize"  
  26.             android:background="@color/colorPrimary"  
  27.             android:elevation="4dp"  
  28.             android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"  
  29.             app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />  
  30.   
  31.     </LinearLayout>  
  32.   
  33.     <com.google.android.material.navigation.NavigationView  
  34.         android:id="@+id/nav_view"  
  35.         android:layout_width="wrap_content"  
  36.         android:layout_height="match_parent"  
  37.         android:layout_gravity="start"  
  38.         app:headerLayout="@layout/nav_header"  
  39.         app:menu="@menu/drawer_menu" />  
  40.   
  41. </androidx.drawerlayout.widget.DrawerLayout> 
In this activity_main.xml file, first, we create Drawer and set the openDrawer as "start". In LinearLayout we create FrameLayout and toolbar for our navigationViewExample project. In the last, we create NavigationView and use nav_header as the header of the NavigationView and also include the menu items file named "drawer_menu".
 
Step 9
 
In the last, here is the MainActivity.java class file of our Android Studio project. The code of MainActivity.java file is listed below.
  1. import androidx.annotation.NonNull;  
  2. import androidx.appcompat.app.ActionBarDrawerToggle;  
  3. import androidx.appcompat.app.AppCompatActivity;  
  4. import androidx.appcompat.widget.Toolbar;  
  5. import androidx.core.view.GravityCompat;  
  6. import androidx.drawerlayout.widget.DrawerLayout;  
  7.   
  8. import android.os.Bundle;  
  9. import android.view.MenuItem;  
  10.   
  11. import com.google.android.material.navigation.NavigationView;  
  12.   
  13. public class MainActivity extends AppCompatActivity implements  
  14.         NavigationView.OnNavigationItemSelectedListener {  
  15.   
  16.     private DrawerLayout drawer;  
  17.   
  18.     @Override  
  19.     protected void onCreate(Bundle savedInstanceState) {  
  20.         super.onCreate(savedInstanceState);  
  21.         setContentView(R.layout.activity_main);  
  22.   
  23.         Toolbar toolbar = findViewById(R.id.toolbar);  
  24.         setSupportActionBar(toolbar);  
  25.   
  26.         drawer = findViewById(R.id.drawer_layout);  
  27.         NavigationView navigationView = findViewById(R.id.nav_view);  
  28.         navigationView.setNavigationItemSelectedListener(this);  
  29.   
  30.         ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,  
  31.                 R.string.navigation_drawer_open, R.string.navigation_drawer_close);  
  32.   
  33.         drawer.addDrawerListener(toggle);  
  34.   
  35.         toggle.syncState();  
  36.   
  37.         if (savedInstanceState == null) {  
  38.             getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,  
  39.                     new MessageFragement()).commit();  
  40.   
  41.             navigationView.setCheckedItem(R.id.nav_message);  
  42.         }  
  43.     }  
  44.   
  45.   @Override  
  46.     public boolean onNavigationItemSelected(@NonNull MenuItem item) {  
  47.             switch (item.getItemId()) {  
  48.                 case R.id.nav_message:  
  49.                     getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,  
  50.                             new MessageFragement()).commit();  
  51.                     break;  
  52.   
  53.                 case R.id.nav_chat:  
  54.                     getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,  
  55.                             new ChatFragment()).commit();  
  56.                     break;  
  57.   
  58.                 case R.id.nav_profile:  
  59.                     getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,  
  60.                             new ProfileFragment()).commit();  
  61.                     break;  
  62.   
  63.                 case R.id.nav_share:  
  64.                     getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,  
  65.                             new ShareFragment()).commit();  
  66.                     break;  
  67.   
  68.                 case R.id.nav_send:  
  69.                     getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,  
  70.                             new SendFragment()).commit();  
  71.                     break;  
  72.             }  
  73.   
  74.   
  75.         drawer.closeDrawer(GravityCompat.START);  
  76.         return true;  
  77.     }  
  78.   
  79.     @Override  
  80.     public void onBackPressed() {  
  81.         if (drawer.isDrawerOpen(GravityCompat.START)) {  
  82.             drawer.closeDrawer(GravityCompat.START);  
  83.         } else {  
  84.             super.onBackPressed();  
  85.         }  
  86.     }  
Explanation
 
In the MainActivity.java file, first, we used toolbar by the line "findViewById(R.id.toolbar)" and set the toolbar in our project by "setSupportSctionBar(toolbar)". We overrode a method named "public boolean onNavigationItemSelected(@NonNull MenuItem item)". For overriding this method we need to implement "NavigationView.OnNavigationItemSelectedListener".
 
We use the switch statement as shown in the MainActivity.java class. As the default home screen of our project, we set the MessageFragment. So when we run our project, a  "Message is Selected" message will be shown on the home screen of our project.
 
Here is the output of the NavigationViewExample. 
 
navigation view example output
 

Summary

 
In this article, we learned about NavigationView in Android with Java Programming Language with an example program in Android Studio.