Open In App

Navigation Drawer in Java Android

Last Updated : 01 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

A Navigation Drawer is the UI panel that can show the app's main navigation menu. When the user swipes from the left edge of the screen or touches the app icon in the action bar and the drawer appears. It can provide a simple way to navigate between the different sections of the application.

This article will guide you through the process of setting up the navigation drawer of Android.

Prerequisites

  • Basic Knowledge of Android development and Java.
  • Android Studio is Installed in your local system.
  • Gradle for building dependency management

Navigation Drawer

The Navigation Drawer in Android is the panel that can slide in from the left edge of the screen and contains the app's main navigation options. It is part of the Material Design guidelines. It can provide a consistent navigation experience across the different Android apps.

Components of the Navigation Drawer

1. DrawerLayout

  • DrawerLayout is the layout container that can handle the sliding behaviour of the navigation drawer of the Android application.
  • It can serve as the root layout for the activity and allows the navigation drawer to slide in from the side of the screen.
  • Attributes:
    • android:layout_gravity: It can specify whether the drawer slides from the left or right edge of the application.
    • android:layout_width and android:layout_height: It can define the dimensions of the drawer.

Example:

<androidx.drawerlayout.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Main content and navigation drawer go here -->
</androidx.drawerlayout.widget.DrawerLayout>

2. NavigationView

  • NavigationView is the widget that displays the contents of the navigation drawer of the android application.
  • It can contains the menu items that the user can click to navigate to the different sections of the app.
  • Attributes:
    • app:menu: It can refers to the menu resource file that defines the items in the drawer of the android app.
    • app:headerLayout: It can refers to the layout resource file that defines the header of drawer and typically containing the user information.

Example:

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

Menu Resource File

The menu resource file can defines the items that will be displayed in the navigation drawer. Each item in menu can represented by the <item> element. we can group items using the <group> elements of the android app.

Example:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/action_home"
        android:icon="@drawable/baseline_home_24"
        android:title="Home" />

        <item
            android:id="@+id/action_settings"
            android:icon="@drawable/baseline_settings_24"
            android:title="@string/action_settings" />
        <item
            android:id="@+id/action_logut"
            android:icon="@drawable/baseline_logout_24"
            android:title="Logout" />

</menu>

Header Layout

The header layout is the optional components that can appears at the top of the navigation drawer. It can typically contains the user information such as the profile picture, username and email.

Example:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="16dp"
    android:background="@drawable/header_background">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Username"
        android:textColor="@android:color/white"
        android:textSize="18sp"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="user@example.com"
        android:textColor="@android:color/white"/>
</LinearLayout>

Step-by-Step Implementation

Step 1: Create a New Android Project

Create the new project in Android Studio refer to How to Create the New Project in Android Studio.

Choose the below options:

  • Language : Java
  • Activity Type : Empty Activity

Once choose the following options then create the android project. Once create the project then file structure looks like the below image

navfile-compressed

Step 2: Layout Files

<?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="wrap_content"
    android:orientation="vertical"
    android:padding="20dp"
    android:background="@color/black"
    android:gravity="bottom">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello User"
        android:textSize="30dp"
        android:textColor="@color/white"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="user@gmail.com"
        android:textSize="20dp"
        android:textColor="@color/white"/>

</LinearLayout>

Header UI

headerUI


<?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"
    tools:context=".MainActivity">

    <!-- Main content -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <!-- Toolbar -->
        <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" />

        <!-- Main content view -->
        <FrameLayout
            android:id="@+id/content_frame"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <!-- TextView -->
            <TextView
                android:id="@+id/sample_text"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Hello, this is a sample Navigation App!"
                android:textSize="18sp"
                android:layout_gravity="center"/>
        </FrameLayout>
    </LinearLayout>

    <!-- Navigation drawer -->
    <com.google.android.material.navigation.NavigationView
        android:id="@+id/nav_menu"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:headerLayout="@layout/header"
        app:menu="@menu/main_menu" />

</androidx.drawerlayout.widget.DrawerLayout>

MainAcitivty UI

maincativtyui

Step 3: Menus

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/action_home"
        android:icon="@drawable/baseline_home_24"
        android:title="Home" />

        <item
            android:id="@+id/action_settings"
            android:icon="@drawable/baseline_settings_24"
            android:title="@string/action_settings" />
        <item
            android:id="@+id/action_logut"
            android:icon="@drawable/baseline_logout_24"
            android:title="Logout" />

</menu>

Menu UI

menuuiii

Step 3: Add the Required Icons

Add the Gallery , Camera and Slideshow button as the resource being used in the Application.

drawwer


Step 6: Add the Nativation Functionality into the MainActivity.

package com.example.simplenavigationapp;

import android.os.Bundle;
import android.view.MenuItem;
import android.widget.Toast;
import androidx.appcompat.widget.Toolbar;

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

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

public class MainActivity extends AppCompatActivity {

    private DrawerLayout drawerLayout;
    private NavigationView navigationView;
    private ActionBarDrawerToggle actionBarDrawerToggle;

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

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

        drawerLayout = findViewById(R.id.drawer_layout);
        navigationView = findViewById(R.id.nav_menu);

        actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawerLayout.addDrawerListener(actionBarDrawerToggle);
        actionBarDrawerToggle.syncState();


        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeButtonEnabled(true);
        }


        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                int itemId = item.getItemId();
                if (itemId == R.id.action_home) {
                    Toast.makeText(MainActivity.this, "Home Selected", Toast.LENGTH_SHORT).show();
                } else if (itemId == R.id.action_settings) {
                    Toast.makeText(MainActivity.this, "Settings Selected", Toast.LENGTH_SHORT).show();
                } else if (itemId == R.id.action_logut) {
                    Toast.makeText(MainActivity.this, "Logout Selected", Toast.LENGTH_SHORT).show();
                }
                drawerLayout.closeDrawers();  // Close the drawer after item is selected
                return true;  // Return true to indicate the item selection has been handled
            }
        });
    }



    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

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

Final Output


Conclusion

The Navigation Drawer is the essential component for the android applications that requires the user friendly and accessible way to the navigate between the different sections. By the using DrawerLayout and NavigationView, we can create the consistent and intuitive navigation experience for the users.


Next Article
Article Tags :

Similar Reads

three90RightbarBannerImg