This blog will explain how to create Custom Navigation Drawer in Android.

Navigation Drawer

Navigation Drawer is a sliding navigation menu by which user can navigate between Activities or Fragments (Screens) in application. It simply like menu of website. You may be seen it in most of android application. It is used to show important links of application to navigate user to and fro.

Prerequisites

  • Android Studio
  • Language Java

You have to have basic knowledge of creating application in Android Studio and Java language.

Please follow below steps to create Android Navigation Drawer.

Step 1. Create Android Project with an empty Activity called MainActivity.  As we have created Activity, two files activity_main.xml and MainActivity.java will be created in its correspondent folders. See project structure given at end of this blog.

Step 2. This is a general setup step you have to do before starting a code.

1. Setup app/build.gradle file by adding com.android.support:design:23.4.0 and com.android.support:support-v4:23.4.0 dependencies. Please see below code to add dependencies. After adding dependencies Sync project.

app/build.gradle

apply plugin: 'com.android.application'

  

android {

    compileSdkVersion 23

    buildToolsVersion "26.0.1"

  

    defaultConfig {

        applicationId "com.example.androidnavigationdrawer"

        minSdkVersion 15

        targetSdkVersion 23

        versionCode 1

        versionName "1.0"

    }

    buildTypes {

        release {

            minifyEnabled false

            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

        }

    }

}

  

dependencies {

    compile fileTree(dir: 'libs', include: ['*.jar'])

    testCompile 'junit:junit:4.12'

    compile 'com.android.support:appcompat-v7:23.4.0'

    compile 'com.android.support:design:23.4.0' /* Add this dependency */

    compile 'com.android.support:support-v4:23.4.0' /* Add this dependency */

}

2. Add color codes in values/colors.xml.

values/colors.xml

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

<resources>

    <color name="colorPrimary">#3F51B5</color>

    <color name="colorPrimaryDark">#303F9F</color>

    <color name="colorAccent">#FF4081</color>

    <color name="colorWhite">#FFFFFF</color>

</resources>

3. Add string in values/strings.xml.

values/strings.xml

<resources>

    <string name="app_name">AndroidNavigationDrawer</string>

    <string name="navigation_drawer_open">Open navigation drawer</string>

    <string name="navigation_drawer_close">Close navigation drawer</string>

</resources>

4. Add themes in values/styles.xml.

values/styles.xml

<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>

    </style>

  

    <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

  

</resources>

5. Add profile image in drawable folder which we will show in Navgation Drawer. To add image in drawable folder copy image and paste it to drawable folder. Give name in small letters. You can see project structure for drawable given at the end of blog.

6. Add fragments to project according to menu of Navigation Drawer. I will create five menus in Drawer so I have added five fragments in project.

Step to add fragment: Right click on app folder (at top of project hierarchy) -> New-> Fragment-> Fragment (Blank). Give proper name click Finish button.

See below code for home fragment.

fragment_home.xml

<LinearLayout 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"

    android:background="#E5E8E8"

    android:gravity="center"

    android:orientation="vertical"

    tools:context=".Home">  

  

    <TextView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Home"

        android:textColor="@color/colorPrimaryDark"

        android:textSize="35dp"

        android:textStyle="bold" />

    <TextView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Hello..!! You are in Home Fragment..!!"

        android:textColor="@color/colorPrimaryDark"

        android:textSize="16dp" />

  

</LinearLayout>

Home.java

package com.example.androidnavigationdrawer;

  

import android.os.Bundle;

import android.support.v4.app.Fragment;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

  

public class Home extends Fragment {

  

    @Override

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        /* Inflate the layout for this fragment */

        return inflater.inflate(R.layout.fragment_home, container, false);

    }

  

}

Please follow same step to create other four (Account, Favorite, AboutUs, ContactUs) fragments.

7. Set theme to AppTheme.NoActionBar in AnddroidManifest.xml file. Please see below code to add theme.

AnddroidManifest.xml

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

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.example.androidnavigationdrawer">

  

    <application

        android:allowBackup="true"

        android:icon="@mipmap/ic_launcher"

        android:label="@string/app_name"

        android:supportsRtl="true"

        android:theme="@style/AppTheme.NoActionBar"> /* Set theme */

        <activity android:name=".MainActivity">

            <intent-filter>

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

  

                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>

        </activity>

    </application>

  

</manifest>

The general setup steps are ending here. Following steps are for creating Navigation Drawer.

Step 3. Before modifying activity_main.xml file, we have to create three supporting resource (.xml) files for Navigation Drawer. Sequentially start creating resource file from content.xml, than appbar.xml and than header.xml.

Step to create xml Layout file: Right click to layout folder->New->Layout resource file.

content.xml

This file is used to show fragment to which user will navigate from Drawer. The LinearLayout available in this file will be replaced with fragment.

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

<LinearLayout 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"

    android:id="@+id/replacableLayout"

    android:orientation="vertical"

    tools:showIn="@layout/activity_main">

  

</LinearLayout>

appbar.xml

This file will used to show application bar at top of screen where navigation icon has been placed and this icon is used to open Navigation Drawer.

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

<LinearLayout 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/appBarLayout"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:fitsSystemWindows="true"

    android:orientation="vertical"

    tools:context=".MainActivity">

  

    <android.support.design.widget.AppBarLayout

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:background="@color/colorPrimary"

        app:theme="@style/AppTheme.AppBarOverlay">

  

        <android.support.v7.widget.Toolbar

            android:id="@+id/ToolBar"

            android:layout_width="match_parent"

            android:layout_height="wrap_content"

            android:titleTextColor="@color/colorWhite">

        </android.support.v7.widget.Toolbar>

  

    </android.support.design.widget.AppBarLayout>

  

    <include layout="@layout/content"></include>

  

</LinearLayout>

header.xml

This file is used to show header content in Navigation Drawer such as profile picture and Username etc...

<?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="150dp"

    android:background="@color/colorAccent"

    android:gravity="left|center"

    android:orientation="vertical"

    android:padding="15dp">

  

    <ImageView

        android:layout_width="60dp"

        android:layout_height="60dp"

        android:src="@drawable/profilepic" />

  

    <TextView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_marginTop="10dp"

        android:text="Dilip Nigam"

        android:textColor="@color/colorWhite"

        android:textSize="16dp" />

  

    <TextView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_marginTop="5dp"

        android:text="dilipnigam@gmail.com"

        android:textColor="@color/colorWhite"

        android:textSize="16dp" />

  

</LinearLayout>

Step 4. Now create a Menu resource (.xml) file to display navigation menu in Navigation Drawer. Give name navigationmenu.xml.

Step to create xml Layout file for Menu: Right click to res folder->New->Layout resource file->Provide name and select menu from Resource type dropdown.

navigationmenu.xml

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

  

    <group

        android:id="@+id/group1"

        android:checkableBehavior="single">

        <item

            android:id="@+id/menuHome"

            android:title="Home"

            app:showAsAction="always" />

        <item

            android:id="@+id/menuAccount"

            android:title="Account" />

        <item

            android:id="@+id/menuFavorite"

            android:title="Favorite" />

    </group>

  

    <group

        android:id="@+id/group2"

        android:checkableBehavior="single">

        <item

            android:id="@+id/menuAboutUs"

            android:title="About Us"

            app:showAsAction="always" />

        <item

            android:id="@+id/menuContactUs"

            android:title="Contact Us" />

    </group>

  

</menu>

Step 5. Open activity_main.xml , modify file by putting below code of Navigation Drawer. This file is become main file for creating Navigation Drawer. We will use android.support.v4.widget.DrawerLayout.

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

<LinearLayout 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:layout_height="match_parent"

    android:orientation="vertical"

    tools:context=".MainActivity">

  

    <android.support.v4.widget.DrawerLayout

        android:id="@+id/drawerLayout"

        android:layout_width="match_parent"

        android:layout_height="match_parent"

        tools:openDrawer="start">

  

        <include

            android:id="@+id/includeSlider"

            layout="@layout/appbar"

            android:layout_width="match_parent"

            android:layout_height="match_parent" />

  

        <android.support.design.widget.NavigationView

            android:id="@+id/navigationView"

            android:layout_width="wrap_content"

            android:layout_height="match_parent"

            android:layout_gravity="start"

            android:fitsSystemWindows="true"

            app:headerLayout="@layout/header"

            app:menu="@menu/navigationmenu" />

  

    </android.support.v4.widget.DrawerLayout>

  

</LinearLayout>

Step 6. Now open MainActivity.java file to code to setup Navigation Drawer in our Activity. Write below code as per following sequence.

  1. Write code to bind menu in onCreate() event.
  2. Set event on menu item selection using setNavigationItemSelectedListener.
  3. Set first fragment which open first when application starts using HomeFragment() function.
  4. Replace LinearLayout available in content.xml file with fragment using setFragmentManager().

package com.example.androidnavigationdrawer;

  

import android.support.design.widget.NavigationView;

import android.support.v4.app.Fragment;

import android.support.v4.app.FragmentManager;

import android.support.v4.view.GravityCompat;

import android.support.v4.widget.DrawerLayout;

import android.support.v7.app.ActionBarDrawerToggle;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.support.v7.widget.Toolbar;

import android.view.MenuItem;

import android.widget.LinearLayout;

import android.widget.Toast;

  

public class MainActivity extends AppCompatActivity {

  

    Toolbar toolbar;

    DrawerLayout drawerLayout;

    LinearLayout appBarLayout;

    NavigationView navigationView;

    ActionBarDrawerToggle toggle;

    Fragment fragment;

    FragmentManager fragmentManager;

  

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

  

        /* Setup Navigation Drawer */

        try {

  

            toolb ar = (Toolbar) findViewById(R.id.ToolBar);

            setSupportActionBar(toolbar);

  

            drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);

            appBarLayout = (LinearLayout) findViewById(R.id.appBarLayout);

            navigationView = (NavigationView) findViewById(R.id.navigationView);

  

            toggle = new ActionBarDrawerToggle(MainActivity.this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) {

            };

            drawerLayout.setDrawerListener(toggle);

            toggle.syncState();

  

        } catch (Exception ex) {

            Toast.makeText(MainActivity.this, ex.toString(), Toast.LENGTH_LONG).show();

        }

  

        /* Setting home fragment to open when application run first time */

        HomeFragment();

  

        /* Setting menu click event of Navigation Drawer */

        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {

            @Override

            public boolean onNavigationItemSelected(MenuItem item) {

  

                fragment = null;

  

                switch (item.getItemId()) {

                    case R.id.menuHome:

                        fragment = new Home();

                        break;

                    case R.id.menuAccount:

                        fragment = new Account();

                        break;

                    case R.id.menuFavorite:

                        fragment = new Favorite();

                        break;

                    case R.id.menuAboutUs:

                        fragment = new AboutUs();

                        break;

                    case R.id.menuContactUs:

                        fragment = new ContactUs();

                        break;

                    default:

                        Toast.makeText(MainActivity.this, "No Data", Toast.LENGTH_LONG).show();

                }

  

                drawerLayout.closeDrawer(GravityCompat.START);

                setFragmentManager();

  

                return true;

            }

        });

  

    }

  

    /* Function to set first fragment */

    public void HomeFragment() {

        fragment = new Home();

        setFragmentManager();

    }

  

    /* Function to replace LinearLayout available in content.xml file with fragment */

    public void setFragmentManager() {

        if (fragment != null) {

            fragmentManager = getSupportFragmentManager();

            fragmentManager.beginTransaction().replace(R.id.replacableLayout, fragment).commit();

        }

    }

}

Your Project Structure may look like,

Step 7. Now run this application in AVD or in your mobile. The output screen shown below.

I hope you like this blog. If you have any query, please comment below. Thank You… :)