Show Sliding Menu Using Navigation View Android Tutorial

Navigation View was introduced with Material Design Support Library. Navigation is very easy to implement , so it is easy to customize it and looks great and is very smooth.

If you are unaware of Material Design visit here.It is necessary you should have knowledge of Material Design.

So, Lets start:- Navigation View has two Main Components i.e Header View and  Menu.

Header View 

This is the top part of Navigation View usually containing Profile Picture and username like in apps like Gmail,Facebook etc.

Menu

The menu is the part below Header View and consists the menu which is defined under res->menu folder. So, Together menu and header view act as a Navigation view containing all  the options for a user.

Requirements:-

1.Open  Android Studio -> New Project->Android Application Project-> Name of Application-> Follow all instructions and complete by clicking on Finish.

2.Make sure your current theme does not have ActionBar by default like mine is Theme.AppCompat.Light.NoActionBar under res->values->styles.xml

3.Now add a dependency in build.gradle to work with material design

compile 'com.android.support:design:23.1.1'

4.Now create header.xml and menu.xml for Navigation View

header.xml under res->layout->header.xml

here i am using imageview and textview to show image and email althought you can change according to your requirements like circleimageview and textview

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#7ac5cd">

    <ImageView
        android:id="@+id/profileimage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/logo"
        android:padding="20dp"
        android:layout_gravity="center"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="coderzpassion@gmail.com"
        android:padding="20dp"/>
</LinearLayout>

menu_main.xml under res->menu->menu_main.xml

<menu 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" tools:context=".MainActivity">
    <group android:checkableBehavior="single">
    <item
        android:id="@+id/home"
        android:title="Home"
        android:checked="false"/>
        <item
            android:id="@+id/inbox"
            android:title="Inbox"
            android:checked="false"/>
        <item
            android:id="@+id/outbox"
            android:title="Outbox"
            android:checked="false"/>
        <item
            android:id="@+id/sent"
            android:title="Sent"
            android:checked="false"/>
        <item
            android:id="@+id/aboutus"
            android:title="About Us"
            android:checked="false"/>
    </group>
</menu>

 Note: here i am using checkableBehavior=”single” to select single menu item you can also use none or all.

5.Now create a layout for activity containing Navigation View.In this i am using DrawerLayout attribute fitsSystemWindows=”true” so that Navigation should come above toolbar also. in this layout i am using Framelayout to contain all fragments and Using Navigation View attribute app:headerLayout=”@layout/header” to set header to Navigation View and app:menu=”menu/menu_main” to set menu items and use layout_gravity=”start” to start Navigation View from left or start.

activity_main.xml

<android.support.v4.widget.DrawerLayout
    android:id="@+id/drawer"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    fitsSystemWindows="true"
    >
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            ></android.support.v7.widget.Toolbar>
        <FrameLayout
            android:id="@+id/container"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        </FrameLayout>
    </LinearLayout>
<android.support.design.widget.NavigationView
    android:id="@+id/navigationview"
    android:layout_height="match_parent"
    android:layout_width="wrap_content"
    android:layout_gravity="start"
    app:headerLayout="@layout/header"
    app:menu="@menu/menu_main"
    ></android.support.design.widget.NavigationView>

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

6. Now Define some Strings to use in our Application under res->values->strings.xml

strings.xml

<resources>
    <string name="app_name">Navigation Sample</string>
    <string name="draweropened">Drawer Opened</string>
    <string name="drawerclosed">Drawer Closed</string>
 
</resources>

7.Now create a layout for fragment which will be shown when you click on MenuItem or you can on options showed on Navigation View.

navigationfragment.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"/>

</LinearLayout>

8.Now create a Fragment for above layout

NavigationFragment

package com.coderzpassion.navigationviewsample;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.TextView;


/**
 * Created by apple on 20/02/16.
 */
public class NavigationFragment extends Fragment {

    String titleforfragment="";

    public NavigationFragment()
    {

    }
public static NavigationFragment newInstance(String title)
{
    NavigationFragment ap=new NavigationFragment();
    Bundle b=new Bundle();
    b.putString("title",title);
    ap.setArguments(b);
    return  ap;
}

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        titleforfragment=getArguments().getString("title");
    }

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

        View rootView = inflater.inflate(R.layout.navigationfragment, container, false);
        TextView title=(TextView)rootView.findViewById(R.id.title);
        title.setText(titleforfragment);

        return rootView;
    }
}

9. Now Code for Navigation View in MainActivity.java

MainActivity.java

package com.coderzpassion.navigationviewsample;

import android.graphics.Color;
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.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    //defining widgets
    private Toolbar toolbar;
    private NavigationView navigationView;
    private DrawerLayout drawerLayout;
    NavigationFragment fragment=null;
    android.support.v4.app.FragmentTransaction fragmentTransaction=null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //initialising the widgets
        toolbar=(Toolbar)findViewById(R.id.toolbar);

        navigationView=(NavigationView)findViewById(R.id.navigationview);
        drawerLayout=(DrawerLayout)findViewById(R.id.drawer);

        //setting the toolbar as actionbar
        setSupportActionBar(toolbar);

        //setting background color of toolbar
        toolbar.setBackgroundColor(Color.parseColor("#0081c9"));

        //handling click of Navigation View items
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(MenuItem menuItem) {
                if(menuItem.isChecked())
                    menuItem.setChecked(false);
                else
                menuItem.setChecked(true);
                drawerLayout.closeDrawers();

                return displayFragment(menuItem.getItemId());
            }
        });

        //creating ActionBarDrawerToggle
        ActionBarDrawerToggle actionBarDrawerToggle=new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.draweropened,R.string.drawerclosed)
        {
            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
            }
        };
        //binding ActionBarDrawerToggle to DrawerLayout
        drawerLayout.setDrawerListener(actionBarDrawerToggle);

        //calling sync state is compulsory to avoid unusual behaviour as home button wont show up
        actionBarDrawerToggle.syncState();

        //showing Fragment for FirstTime
        if(savedInstanceState==null)
        {
            displayFragment(R.id.inbox);
        }

    }

    public boolean displayFragment(int id)
    {
        switch (id)
        {
            case R.id.home:
                Toast.makeText(getApplicationContext(), "Home Selected", Toast.LENGTH_SHORT).show();
                fragment=NavigationFragment.newInstance("Home");
                fragmentTransaction = getSupportFragmentManager().beginTransaction();
                fragmentTransaction.replace(R.id.container,fragment);
                fragmentTransaction.commit();
                return true;
            case R.id.inbox:
                Toast.makeText(getApplicationContext(), "Inbox Selected", Toast.LENGTH_SHORT).show();
                fragment=NavigationFragment.newInstance("Inbox");
                fragmentTransaction = getSupportFragmentManager().beginTransaction();
                fragmentTransaction.replace(R.id.container,fragment);
                fragmentTransaction.commit();
                return true;
            case R.id.outbox:
                Toast.makeText(getApplicationContext(), "Outbox Selected", Toast.LENGTH_SHORT).show();
                fragment=NavigationFragment.newInstance("Outbox");
                fragmentTransaction = getSupportFragmentManager().beginTransaction();
                fragmentTransaction.replace(R.id.container,fragment);
                fragmentTransaction.commit();
                return true;
            case R.id.sent:
                Toast.makeText(getApplicationContext(), "Sent Selected", Toast.LENGTH_SHORT).show();
                fragment=NavigationFragment.newInstance("Sent");
                fragmentTransaction = getSupportFragmentManager().beginTransaction();
                fragmentTransaction.replace(R.id.container,fragment);
                fragmentTransaction.commit();
                return true;
        }
        return false;
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
     //   getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        return super.onOptionsItemSelected(item);
    }
}

Output

slidingmenuusingnavigationview  androidhowtoshowslidingmenuusingnavigationview