Android Navigation Drawer example

As you know lot of android applications introduced a sliding panel menu to navigate between major modules of the application. Previously this kind of UI was done using some third party libraries where a list view and some swiping gestures used to achieve this. But now android  introduced sliding panel menu by introducing a newer concept called Navigation Drawer in which we combine DrawerLayout and NavigationView to achieve the desired output.

The navigation drawer is a UI panel that shows your app’s main navigation menu. Most of the time Sliding Menu (Navigation Drawer) will be hidden and can be shown by swiping the screen from left edge to right or tapping the app icon on the action bar.

In this tutorial I will show you how to implement a navigation drawer using the DrawerLayout APIs available in the Support Library.

Get GITHUB code from here.

 

Create new Project

1. Create a new project in Android Studio from File ⇒ New Project by filling the required details. When it prompts you to select the activity, choose Empty Activity and continue.

2. Open build.gradle located in app level and add below dependencies. These dependencies are needed for navigation drawer.

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support:design:27.1.1'
    implementation 'com.android.support:support-v4:27.1.1'
}

Creating Fragments & Activities

3. Create  package  fragment which contains all the fragment and leave MainActivity.java in root package.

4.. Create all the fragment classes needed for navigation menu. Overall I am creating five fragment classes. Right click on fragment package, NewFragmentFragment (Blank) and name it as HomeFragment.java. This fragment will be loaded always whenever user open the app.

Likewise create other fragments named ImportFragmentGalleryFragment, SlideshowFragment and ToolsFragment .

5. In our navigation drawer menu, there are two other menu items, SendActivity and ShareActivity. For these two we are gonna create activities instead of fragments. Create new two activities named SendActivity.java and ShareActivity.java.

Adding Navigation Drawer

6. Under resmenu directory, create a menu xml file named activity_main_drawer.xml. This menu renders the Navigation Drawer list items. Here we set the icons and labels. You can also notice here <group>is used to combine multiple items under single levels. An <item> also can be used to group multiple child items with a title. This provides a horizontal separator between the two sets.

activity_main_drawer.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="navigation_view">

    <group android:checkableBehavior="single">
        <item
            android:id="@+id/nav_home"
            android:icon="@drawable/home2"
            android:title="Home"

            />

        <item
            android:id="@+id/nav_import"
            android:icon="@drawable/ic_menu_import"
            android:title="Import"

            />
        <item
            android:id="@+id/nav_gallery"
            android:icon="@android:drawable/ic_menu_gallery"
            android:title="Gallery" />
        <item
            android:id="@+id/nav_slideshow"
            android:icon="@android:drawable/ic_menu_slideshow"
            android:title="Slideshow" />
        <item
            android:id="@+id/nav_tools"
            android:icon="@drawable/tools"
            android:title="Tools"

            />

    </group>

    <item android:title="Communicate">
        <menu>
            <item
                android:id="@+id/nav_share"
                android:icon="@android:drawable/ic_menu_share"
                android:title="Share" />
            <item
                android:id="@+id/nav_send"
                android:icon="@android:drawable/ic_menu_send"
                android:title="Send" />

        </menu>

    </item>
</menu>

7. Under res ⇒ layout, create a file named nav_header_main.xml This layout renders the navigation drawer header part with a profile image, name and email.

nav_header_main.xml

<?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="176dp"
    android:background="@drawable/background">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="20dp"
        android:layout_marginLeft="8dp"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/img_profile"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:src="@drawable/profile" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignRight="@+id/img_profile"
            android:layout_marginLeft="8dp"
            android:orientation="vertical">


            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:text="Arun Kumar"
                android:textColor="@android:color/white"
                android:textSize="18sp"
                android:textStyle="bold" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:text="arunkumar@gmail.com"
                android:textColor="@android:color/white"
                android:textSize="15sp"
                android:textStyle="bold" />
        </LinearLayout>
    </LinearLayout>
</RelativeLayout>

8. Now we’ll create another layout file to add required Toolbar and FrameLayout. FrameLayout is used to load appropriate fragment when an item is selected from nav menu. Create a layout file named app_bar_main.xml under res ⇒ layout.

app_bar_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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.support.design.widget.AppBarLayout
        android:id="@+id/appbar_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/MyMaterialTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/MyMaterialTheme.PopupOverlay" />

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

    <FrameLayout
        android:id="@+id/frame_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/appbar_layout">

    </FrameLayout>


</RelativeLayout>

9. Open the layout file of your main activity activity_main.xml and add NavigationView element. You can notice that the toolbar layout is added using <include> tag.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.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:openDrawer="start"
    tools:context="com.c1ctech.navigationdrawerexample.MainActivity"
  >

    <include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer" />

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

10. Now we have all the required elements in place. It’s time to open the main activity and do the necessary changes to make the navigation drawer functional. Open MainActivity.java and modify as explained below.

MainActivity.java

package com.c1ctech.navigationdrawerexample;

import android.content.Intent;
import android.support.design.widget.NavigationView;
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 com.c1ctech.navigationdrawerexample.fragment.ToolsFragment;
import com.c1ctech.navigationdrawerexample.fragment.GalleryFragment;
import com.c1ctech.navigationdrawerexample.fragment.HomeFragment;
import com.c1ctech.navigationdrawerexample.fragment.ImportFragment;
import com.c1ctech.navigationdrawerexample.fragment.SlideshowFragment;


public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

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

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

        //setting home as default fragment
        getSupportActionBar().setTitle("Home");
        HomeFragment home_fragment = new HomeFragment();
        getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout, home_fragment).commit();

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);

        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        //called when any of the given navigation items selected
        navigationView.setNavigationItemSelectedListener(this);
    }

    //onBackPress operation
    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        //if navigationDrawer is open then it will close it
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onNavigationItemSelected(MenuItem item) {

        int id = item.getItemId();

        if (id == R.id.nav_home) {
            getSupportActionBar().setTitle("Home");
            HomeFragment home_fragment = new HomeFragment();
            getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout, home_fragment).commit();

        } else if (id == R.id.nav_import) {
            getSupportActionBar().setTitle("Import");
            ImportFragment import_fragment = new ImportFragment();
            getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout, import_fragment).commit();
        } else if (id == R.id.nav_gallery) {
            getSupportActionBar().setTitle("Gallery");
            GalleryFragment gallery_fragment = new GalleryFragment();
            getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout, gallery_fragment).commit();
        } else if (id == R.id.nav_slideshow) {
            getSupportActionBar().setTitle("Slideshow");
            SlideshowFragment slideshow_fragment = new SlideshowFragment();
            getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout, slideshow_fragment).commit();
        } else if (id == R.id.nav_tools) {
            getSupportActionBar().setTitle("Tools");
            ToolsFragment tools_fragment = new ToolsFragment();
            getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout, tools_fragment).commit();
        } else if (id == R.id.nav_share) {

            Intent intent = new Intent(this, ShareActivity.class);
            startActivity(intent);
        } else if (id == R.id.nav_send) {
            Intent intent = new Intent(this, SendActivity.class);
            startActivity(intent);
        }
        //when item is selected then it will close the drawer
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);

        return true;
    }
}

 

When you run the app it will look like this as shown below :

Leave a Reply