Navigation Drawer In Android Studio

Imagine a country without a map, it would be difficult to go to new places, explore new restaurants. In short, it would be difficult to navigate such a country.

So imagine an app without a navigation, you wouldn't be able to navigate and explore the features of an app or you would have to create seperate apps to implement features. Doesn't make sense right. So this shows the importance of a navigation to an app and in this article we would be exploring a navigation drawer.

What is a Navigation Drawer?

A navigation drawer is common feature in android. It is used to provide access to destinations in an application such as switching accounts, logout etc. A user can view a navigation drawer when they swipe the left edge of an activity or by tapping the hamburger menu in the action bar.

Prerequisites

  • Android Studio

  • Java 8 language features

Steps to Implement a Navigation Drawer in Android Studio

  1. Create an Android Studio Project

    To create an android project, click File, click on New, click on New Project, select empty activity, click Next, then give a name to your project and choose java as the language, then click on Finish.

  2. Create a Menu Folder

    To create a menu folder, right click on app, then click on New, then click on Android Resource directory and select Resource type as menu then click OK.

  3. Create a menu inside the menu folder

    To create a menu, right click on the menu folder , click on New, click on Menu Resource File and name your file "drawer_menu" then click Ok.

  4. Write the following code in the drawer_menu.xml

<?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="true">

<!--    the checkableBehavior attribute
        ensures only one item is clicked at a time-->
    <group android:checkableBehavior="single"  >

        <item android:id="@+id/nav_home"
            android:icon="@drawable/ic_home"
            android:title="@string/home" />

        <item android:id="@+id/nav_profile"
            android:icon="@drawable/ic_profile"
            android:title="@string/profile" />

        <item android:id="@+id/nav_account"
            android:icon="@drawable/ic_account"
            android:title="@string/account" />
    </group>

<!--    any item below the group tag is mostly used for 
      performing actions like send, logout etc-->
    <item android:title="">
        <menu>
           <item
               android:id="@+id/nav_logout"
               android:icon="@drawable/ic_logout"
               android:title="@string/logout"/>
        </menu>
    </item>

</menu>

5. Create a Vector Asset in the drawable folder

To create a vector asset, right click on the drawable folder, click on New, click on Vector Asset, click on clip Art, select an icon and click OK.

6. Include the following in the strings.xml file

<resources>
    <string name="app_name">NavigationDrawer</string>
    <string name="home">Home</string>
    <string name="profile">Profile</string>
    <string name="account">Account</string>
    <string name="logout">Log out</string>
    <string name="open_drawer">Open Drawer</string>
    <string name="close_drawer">Close Drawer</string>
    <!-- TODO: Remove or change this placeholder text -->
    <string name="hello_blank_fragment">Hello blank fragment</string>
</resources>

7. Create a toolbar in the layout folder

Create an xml file called "drawer_toolbar" in the layout folder and insert the code below


<?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="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/teal_700"
        android:theme="@style/ThemeOverlay.AppCompat.Dark" />

</LinearLayout>

8. Create a header for the navigation drawer in the layout folder

Create an xml file called "drawer_header" in the layout folder and insert the code below


<?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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:background="@color/teal_700"
    android:layout_height="150dp">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:src="@drawable/ic_profile"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="60dp"
        android:text="Peter Ahunanya"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/imageView"
        android:textSize="20sp"
         />
</androidx.constraintlayout.widget.ConstraintLayout>

9. Create an xml file called "content_main" in the layout folder

This xml file would hold the FrameLayout which would enable us to switch between fragments as we navigate the app.

<?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="match_parent"
    android:orientation="vertical">

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

</LinearLayout>

10. Working with the activity_main.xml file

Invoke the following code in the activity_main.xml to set up the basic things required for the Navigation Drawer.

<?xml version="1.0" encoding="utf-8"?>

<!--    the root view must be a Drawer layout -->
<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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

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

        <!--    include the layout toolbar   -->
        <include
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            layout="@layout/drawer_toolbar"/>

        <!-- include the content_main xml file that holds the
            frame layout to switch between fragments-->
        <include
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            layout="@layout/content_main" />

    </LinearLayout>

<!--    this is the navigation view which draws and shows the
         navigation drawer-->
<!--    the navigation view contains the menu and header layout-->
    <com.google.android.material.navigation.NavigationView
        android:id="@+id/navigation_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/drawer_header"
        app:menu="@menu/drawer_menu">
    </com.google.android.material.navigation.NavigationView>

</androidx.drawerlayout.widget.DrawerLayout>

11. Working with the MainActivity.java file

Invoke the following code in the MainActivity.java file

package com.example.navigationdrawer;

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 androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

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

public class MainActivity extends AppCompatActivity implements  NavigationView.OnNavigationItemSelectedListener{

    DrawerLayout drawerLayout;
    ActionBarDrawerToggle toggle;
    Toolbar toolbar; // make sure to select the androidx.appcompat.widget
    NavigationView navigationView;
    FragmentManager fragmentManager;
    FragmentTransaction fragmentTransaction;
    Intent intent;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        toolbar = findViewById(R.id.toolbar);
        navigationView = findViewById(R.id.navigation_view);
        // to set the action bar to the toolbar
           setSupportActionBar(toolbar);

        drawerLayout = findViewById(R.id.drawer);

       // to set the ActionBarToggle
        toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_drawer, R.string.close_drawer);

        // to enable listener to the navigation drawer, slide right to open and slide left to close
        drawerLayout.addDrawerListener(toggle);

        // to listen to click events in the navigation drawer
        navigationView.setNavigationItemSelectedListener(this);


        // to display the hamburger sign/symbol
        toggle.setDrawerIndicatorEnabled(true);

        toggle.syncState();

        // load default fragment
        fragmentManager =  getSupportFragmentManager();
        fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.add(R.id.container_fragment, new HomeFragment());
        fragmentTransaction.commit();
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();
        if(id == R.id.nav_home){
            fragmentManager = getSupportFragmentManager();
            fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.container_fragment, new HomeFragment());
            fragmentTransaction.commit();
        }

        if(id == R.id.nav_profile){
            fragmentManager = getSupportFragmentManager();
            fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.container_fragment, new ProfileFragment());
            fragmentTransaction.commit();
        }

        if(id == R.id.nav_account){
            fragmentManager = getSupportFragmentManager();
            fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.container_fragment, new AccountFragment());
            fragmentTransaction.commit();

        }

        if(id == R.id.nav_logout){
            Toast.makeText(MainActivity.this, "Logout", Toast.LENGTH_SHORT).show();
        }
        return true;
    }
}

12. Working in the Themes.xml file
The default action bar in the themes.xml file wouldn't allow the toolbar become the new action bar therefore leading to an error. Therefore we create a new style in the themes.xml and give it an attribute of "NoActionBar" and include it in the manifest file.

<resources xmlns:tools="http://schemas.android.com/tools">
    <!-- Base application theme. -->
    <style name="Theme.NavigationDrawer" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Primary brand color. -->
        <item name="colorPrimary">@color/purple_500</item>
        <item name="colorPrimaryVariant">@color/purple_700</item>
        <item name="colorOnPrimary">@color/white</item>
        <!-- Secondary brand color. -->
        <item name="colorSecondary">@color/teal_200</item>
        <item name="colorSecondaryVariant">@color/teal_700</item>
        <item name="colorOnSecondary">@color/black</item>
        <!-- Status bar color. -->
        <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
        <!-- Customize your theme here. -->
    </style>

    <style name="Theme.NavigationDrawer.NoActionBar" parent="Theme.MaterialComponents.DayNight.NoActionBar">
        <!-- Primary brand color. -->
        <item name="colorPrimary">@color/purple_500</item>
        <item name="colorPrimaryVariant">@color/purple_700</item>
        <item name="colorOnPrimary">@color/white</item>
        <!-- Secondary brand color. -->
        <item name="colorSecondary">@color/teal_200</item>
        <item name="colorSecondaryVariant">@color/teal_700</item>
        <item name="colorOnSecondary">@color/black</item>
        <!-- Status bar color. -->
        <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
        <!-- Customize your theme here. -->
    </style>
</resources>
  • Go into the AndroidManifest.xml
<!--  Add a android:theme attribute to the activity tag and give it the name
of the new theme created-->

        <activity
            android:name=".MainActivity"
            android:theme="@style/Theme.NavigationDrawer.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

13. Create the Fragments

To create the fragments, right click on app, click on New, click on Fragment, select Fragment(blank), give a name to the fragment and click Finish.

Preview of fragment_home.xml file

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".HomeFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:textSize="30sp"
        android:text="Home Fragment" />

</FrameLayout>

Preview of HomeFragmet.java file

package com.example.navigationdrawer;

import android.os.Bundle;

import androidx.fragment.app.Fragment;

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

public class HomeFragment extends Fragment {

    public HomeFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
       View view = inflater.inflate(R.layout.fragment_home, container,false);
       return view;
    }
}

Conclusion

In this tutorial, you learned how to create a navigation drawer in Android from scratch. I highly recommend checking out the [ documentation ] to learn more about how to properly design and use navigation drawers in Android.

Thanks for reading, Like, comment and share and watch out for more articles from me.