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. On the first screen, there is an Activity that shows the message "Message is Selected" and the toolbar" NavigationViewExample" on the left side of the toolbar with three lines. On 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.

apply plugin: 'com.android.application'

android {
    compileSdkVersion 29

    defaultConfig {
        applicationId "manigautam.apps.navigationviewexample"
        minSdkVersion 21
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'com.google.android.material:material:1.2.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

}
Java

We add the material dependency in the 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 to 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 the styles.xml file.

<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

        <style name="AppTheme.NoActionBar">
            <item name="windowActionBar">false</item>
            <item name="windowNoTitle">true</item>
            <item name="android:statusBarColor">@android:color/transparent</item>

        </style>

</resources>
XML

Step 4. We will change the theme of the project in our manifest.xml file. So here is the code example of the manifest.xml file of the project.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="manigautam.apps.navigationviewexample">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity"
          android:theme="@style/AppTheme.NoActionBar">

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
XML

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 the nav_header.xml file.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="176dp"
    android:background="@color/colorAccent"
    android:gravity="bottom"
    android:orientation="vertical"
    android:padding="16dp"
    android:theme="@style/ThemeOverlay.AppCompat.Dark">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@mipmap/ic_launcher_round" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="8dp"
        android:text="User Name"
        android:textAppearance="@style/TextAppearance.AppCompat.Body1" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="" />

</LinearLayout>
XML

Step 6. After creating the NavigationView header, we will create a menu file named drawer_menu to add the menu items for the NavigationView. Here is the code of the drawer_menu.xml file.

<?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_message"
            android:icon="@drawable/ic_message"
            android:title="Message" />
        <item
            android:id="@+id/nav_chat"
            android:icon="@drawable/ic_chat"
            android:title="Chat" />
        <item
            android:id="@+id/nav_profile"
            android:icon="@drawable/ic_profile"
            android:title="Profile" />

    </group>
    <item android:title="Commnuicate">
        <menu>
            <item
                android:id="@+id/nav_share"
                android:icon="@drawable/ic_share"
                android:title="Share" />

            <item
                android:id="@+id/nav_send"
                android:icon="@drawable/ic_send"
                android:title="Send" />
        </menu>
    </item>
</menu>
XML

Here, we make two groups in our menu file. In the first group, we created three items: message, chat, and profile. In the second group, we create two items: name share and send. We add a title, id, and an icon for every item. For icons, we add some icons in our drawable file, and we can also use images as the icons; for this, we have to add the images in our project's drawable file.

Step 7. Now, we will create the Fragment Java classes and layouts for these fragments for every item that we add to 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.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/holo_orange_dark">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Message is Selected"
        android:textSize="30sp" />
</RelativeLayout>
XML

In this fragment layout file, we will show a message through the TextView that "Message is Selected". Now, let's look at the fragment Java class named MessageFragment.java.

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class MessageFragement extends Fragment {

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_message, container, false);
    }
}
Java

Now, here is the layout file named fragment_chat.xml file for the Chat item.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/holo_blue_dark">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Chat is Selected"
        android:textSize="30sp" />

</RelativeLayout>
Java

In this fragment layout file, we will show a message through the TextView that "Chat is Selected". Now, let's look at the fragment Java class named ChatFragment.java.

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class ChatFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragemnt_chat,container,false);
    }
}
Java

Now, here is the layout file named fragment_profile.xml file for the profile item. 

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/holo_purple">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Profile is Selected"
        android:textSize="30sp"
        android:layout_centerInParent="true"
        />

</RelativeLayout>
XML

In this fragment layout file, we will show a message through the TextView that "Profile is Selected". Now, let's look at the fragment Java class named ProfileFragment.java.

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class ProfileFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_profile,container,false);
    }
}
Java

Now, here is the layout file named fragment_share.xml file for the Share item.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Share"
        android:textSize="30sp"
        android:layout_centerInParent="true"
        />

</RelativeLayout>
Java

In this fragment layout file, we will show a message. "Share,"  through the TextView. Now, let's look at the fragment Java class named ShareFragment.java.

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class ShareFragment extends Fragment {
        @Nullable
        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            return inflater.inflate(R.layout.fragment_share,container,false);
        }
}
Java

Now, here is the layout file named fragment_send.xml file for the Send item.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/holo_orange_light">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Send"
        android:textSize="30sp"
        android:layout_centerInParent="true"
        />

</RelativeLayout>
XML

In this fragment layout file, we will show a message, "Send," through the TextView. Now, let's look at the fragment Java class named SendFragment.java.

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class SendFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_send, container, false);
    }
}
Java

So, these are the fragment layouts and the Java Fragment files for all the items that 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.

<?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"
    tools:openDrawer="start">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <FrameLayout
            android:id="@+id/fragment_container"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

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

    </LinearLayout>

    <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"
        app:headerLayout="@layout/nav_header"
        app:menu="@menu/drawer_menu" />

</androidx.drawerlayout.widget.DrawerLayout>
XML

In this activity_main.xml file, first, we create a Drawer and set the openDrawer as "start". In LinearLayout, we create FrameLayout and a 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 the MainActivity.java file is listed below.

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;

import android.os.Bundle;
import android.view.MenuItem;

import com.google.android.material.navigation.NavigationView;

public class MainActivity extends AppCompatActivity implements
        NavigationView.OnNavigationItemSelectedListener {

    private DrawerLayout drawer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

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

        drawer = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
                R.string.navigation_drawer_open, R.string.navigation_drawer_close);

        drawer.addDrawerListener(toggle);

        toggle.syncState();

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                    new MessageFragement()).commit();

            navigationView.setCheckedItem(R.id.nav_message);
        }
    }

  @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.nav_message:
                    getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                            new MessageFragement()).commit();
                    break;

                case R.id.nav_chat:
                    getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                            new ChatFragment()).commit();
                    break;

                case R.id.nav_profile:
                    getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                            new ProfileFragment()).commit();
                    break;

                case R.id.nav_share:
                    getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                            new ShareFragment()).commit();
                    break;

                case R.id.nav_send:
                    getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                            new SendFragment()).commit();
                    break;
            }


        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public void onBackPressed() {
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }
}
Java

Explanation

In the MainActivity.java file, first, we used the 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)". To override 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.

Up Next
    Ebook Download
    View all
    Learn
    View all