android tutorial navigation drawer

How to Create Android Navigation Drawer- Simplest way

Android Navigation Drawer

Actually, Android Navigation drawer is a combination of two things – Drawer layout and Navigation view. There Important point is Navigation View is a optional element of main Drawer layout. You can Replace it it with ListView, Expandable Listview, LinearLayout with child like textview, editttext etc. You can define your custom design for drawer layout which will be open from left side of the screen.

Android Drawer Layout

The side bar that open from the left side of screen is a blank container which is known as Drawer Layout. So on activity layout xml file, you need to create Drawer layout as main layout. Drawer layout it part of android support design library to first you need to add dependency on your app(module) gradle file. Please add this line of code on app-module gradle file.

// if android studio is 3.0.1 or greater    
implementation 'com.android.support:design:26.1.0'

// else
  compile 'com.android.support:design:26.1.0'




Android Navigation drawer video tutorial

Login & Download source code

download-code350-100

android course

 

1) Add Support design Dependency
2) Create Drawer layout & Navigation view
3) Add Support Toolbar & Drawer toggle listener
4) Add Menu item click listener
5) Run App on device

Add Support design Dependency

First you need to add android support design dependency on app module gradle file. Once it is done the drawerlayout tag will be visible on xml layout file.

Create Drawer layout & Navigation view

Open activity Main layout file and first parent tag will be drawerlayout. Inside drawer layout you need to add 3 things( you have option to use default actionbar in place of toolbar). The Design hierarchy will look like that –

<drawerlayout
  
    <Coordinatelayout
      <AppBar
          <Toolbar>  </toolbar>
      </Appbar>
      <Linearlayout or relative layout anything you can use here
             // you main screen design here
      </Linearlayout>
   </Cordinatelayout>

 
   
   <NavigationView
   </NavigationView>

</drawerLayout>

There few important android property you have to add otherwise android navigation drawer won’t work correctly.
1) on drawerlayout tag use android:fitsSystemWindows=”true”
2) on NavigationView tag use android:layout_gravity=”start”

Please have a look on below code. On Navigationview you will see app:headerLayout=”@layout/nav_header” and app:menu=”@menu/nav_menu”. So if you want a headerlayout which container user profile pic ,name and logout button so you need to create a layout file nav_header(you can name it anything). Now pass the header layout file name on app:headerLayout= “layout name here “.

Now to display menu option on android navigation drawer you need to create a android resource directory inside res folder. Right click on res folder and create android resource folder. now click on second dropdown list and select menu. it will create a menu folder. Now right click on menu folder and create new menu resource file. I gave the file name nav_menu. now set this property on navigationview app:menu=”@menu/nav_menu”.

<?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.support.design.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="?attr/colorPrimary"
                app:navigationIcon="@mipmap/ic_launcher"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light" >

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

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

       <LinearLayout
           android:layout_width="match_parent"
           android:layout_height="match_parent"
           android:orientation="vertical">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:id="@+id/fragContainer"
                android:orientation="vertical">
            </LinearLayout>

       </LinearLayout>

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

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

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

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

Add Toolbar And Drawer toggle Listener

Now You have two options either use toolbar or actionbar. I will suggest you to go with Toolbar because it will give you more flexibility to customize app. Now on MainActivity java file set toolbar as default actionbar using this code.

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

Now Set toggle Listener to drawer layout. Toggle means when user click outside the navigation drawer, the drawer layout will auto close. To achieve this task you need to pass 5 parameters to new ActionBarDrawerToggle (Important – If you are using toolbar the pass 5 parameter otherwise if using default actionbar then you can pass 4 parameter- means 3rd param toolbar you don’t need to use it).

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

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

         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.navigation_view);
         navigationView.setNavigationItemSelectedListener(this);
    }

Add Menu Item Click Listner

We are almost ready, Now it is time to add click listener on menu item. You can implement NavigationView.OnNavigationItemSelectedListener on main activity class. after that system will promote you to overwrite the method public boolean onNavigationItemSelected(@NonNull MenuItem item). You have MenuItem as a parameter in this method. So you can use it to identify the menu name which user is clicking. Below is the complete code for navigation drawer click listener.

package blueappsoftware.navidrawerr;

import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
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.util.Log;
import android.view.MenuItem;

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

         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.navigation_view);
         navigationView.setNavigationItemSelectedListener(this);
    }


    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {

        int id = item.getItemId();
        if (id == R.id.price){
            Log.e("mainactivity "," price menu click ");

        }else if (id == R.id.product){
            Log.e("mainactivity "," product menu click ");
        }

        switch (id){
            case R.id.rating:
                Log.e("mainactivity "," rating menu click ");
                break;
            case R.id.aboutus:
                Log.e("mainactivity "," about us menu click ");
                break;
        }

        DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawerLayout.closeDrawers();
        return true;
    }
}

Run the Code

Now run the code, so you will get navigation drawer on left top corner. If you can seeing navigation drawer over entire screen that means you forgot to call android:layout_gravity=”start”. Also it your drawer layout is not closing on outside click that means you missed the toggle syncstate() property on MainActivity.java.
If you have any other question you can ask me.

android course

Do you want payment gateway integration?

Instamojo Payment Gateway
How to Integrate Paytm Payment gateway

Posted in andorid and tagged , , , , .

I Am Post Graduation (M.Tech. C.S.E) from VNIT, Nagpur. I Have Published Two Research Paper On International Journal. My Apps on Google Play Store- Sanyukt Parivar(Mp Police ), NOTOtag- Digital Chhindwara, The Tubby-VoiceRecognizer & More.
Contact me at kamal.bunkar@blueappsoftware.in

33 Comments

  1. I love your blog.. very nice colors & theme. Did you create this
    website yourself or did you hire someone to do it for you?
    Plz respond as I’m looking to create my own blog and would like to find
    out where u got this from. appreciate it

  2. Pretty great post. I just stumbled upon your weblog and wanted to say
    that I’ve truly loved browsing your blog posts.
    In any case I’ll be subscribing for your feed and I hope you write once more very soon!

  3. Hi there! This post could not be written any better!
    Reading through this post reminds me of my good old room mate!
    He always kept talking about this. I will forward this article to him.
    Fairly certain he will have a good read. Thank you for sharing!

  4. Hi there! Quick question that’s totally off topic.
    Do you know how to make your site mobile friendly?
    My weblog looks weird when browsing from my iphone4.
    I’m trying to find a template or plugin that might
    be able to fix this issue. If you have any recommendations, please share.
    Thank you!

  5. This is really attention-grabbing, You are an overly skilled blogger.
    I have joined your feed and look forward to in the hunt
    for extra of your great post. Also, I have shared your site in my social networks

  6. I’m really enjoying the theme/design of your blog.

    Do you ever run into any browser compatibility issues?

    A few of my blog audience have complained about my site not
    working correctly in Explorer but looks great in Chrome.
    Do you have any solutions to help fix this issue?

  7. I was recommended this web site by my cousin. I’m
    not sure whether this post is written by him as no one else
    know such detailed about my problem. You are wonderful!

    Thanks!

  8. Hey I know this is off topic but I was wondering if you knew of any widgets I could add to my blog that automatically tweet my newest twitter updates.
    I’ve been looking for a plug-in like this for quite some time and was hoping maybe you would have some experience with something like this.
    Please let me know if you run into anything. I truly enjoy reading your
    blog and I look forward to your new updates.

  9. Having read this I thought it was very informative. I appreciate you finding the time and
    energy to put this short article together. I once again find myself personally spending a lot of time both reading and posting comments.
    But so what, it was still worthwhile!

  10. hi! may i know is your code complete? because i run the program and does nothing, i have download the given source code.

    • Yes this code is working…You have to create file on php server to store FCM key into your database for future use. First check on your android studio log whether FCM token is printing OR not. If it is printing in log than send token to your web server.

  11. Good day! I could have sworn I’ve been to
    this website before but after going through
    a few of the articles I realized it’s new to me.

    Nonetheless, I’m certainly delighted I found it and I’ll be book-marking it and checking back regularly!

  12. Spot on with this write-up, I absolutely feel this website needs much more attention. I’ll probably be returning to read
    through more, thanks for the info!

  13. Hey very cool website!! Man .. Excellent ..
    Amazing .. I will bookmark your site and take the feeds additionally?
    I am glad to search out numerous useful info here
    in the submit, we need work out more strategies
    on this regard, thanks for sharing. . . . . .

  14. Pingback: ExoPlayer Android Example- Best Alternative of VideoView By Kamal

  15. Pingback: Simplest way to get WordPress Post in Android App- REST API

  16. I just like the helpful information you supply to your articles.

    I’ll bookmark your blog and test once more here frequently.
    I’m fairly sure I will learn many new stuff proper here!
    Good luck for the following!

Comments are closed.