Android NavigationView Tutorial With Example

Android NavigationView represents a standard navigation menu for application. It is one of the way to implement navigation hierarchy on Android applications, some of the others are Tabs, Spinners etc.
Before Android NavigationView, It was difficult to implement material navigation drawer using list view or linear layout with custom adapter. Now it can be implemented easily using android NavigationView. We just need to add NavigationView widget in DrawerLayout and add header layout, menu etc. in it.

Output

Tutorialwing - Android NavigationView Tutorial Output

Tutorialwing – Android NavigationView Tutorial Output

Video Output

Source Code

NavigationView Tutorial Source Code

1. Getting started

In this tutorial, you will learn how to use android NavigationView in applications. We have also how to use left as well as right NavigationView in android application.

Since NavigationView is placed inside a DrawerLayout, you need to know about DrawerLayout to understand how does NavigationView work.

Android DrawerLayout

DrawerLayout is a subclass of ViewGroup that acts as a top level container for window content. It also allows drawer to be pulled from one or both vertical edges of the window.
To use a DrawerLayout, position your primary content view as first child with width and height of match_parent and no layout_gravity. Add drawers as child view after the main content view and set layout_gravity(left or right) appropriately.

<android.support.v4.widget.DrawerLayout
———————————
———————————
>
<!— Primary content with width and height of match_parent and no layout_gravity—>
<!— Drawer with proper layout_gravity(left or right) —>
</android.support.v4.widget.DrawerLayout>

You can use DrawerLayout.DrawerListener to monitor the state and motion of drawer views.
As per the Android Design Guide, any drawer positioned to the left/start should always contain content that helps in navigating around the application, whereas any drawer positioned to the right/end should always contain content that helps in performing some actions on the current content.
You can see Android design guide for navigation drawer in this link

Android NavigationView has two main components.
a. HeaderView : HeaderView is top part of the NavigationView, which generally contains user related informations e.g. profile picture, name, email-id etc. At first, we need to define a separate layout for it in res/layout folder. Then, we provide reference to this file using app:headerLayout=“”. We will soon see how to create header-view.

b. Menu : This is the view that we show below HeaderView. Menu contains list of items (that has some specific name, image etc.). At first we create menus in a separate xml file in res/menu folder. Then, we provide reference to this file using app:menu=”” in NavigationView.

Attributes in Android NavigationView

app:menu=”” : Set the menu resource to the drawer. e.g. @menu/drawer_menu.xml etc.
app:headerLayout=”” : Set the header view of the NavigationView. We can set any custom view in it.

app:itemBackground=”” : Set the background to menu item in the drawer.
app:itemIconTint=”” : Change the icon color of the menu item in the drawer.
app:itemTextColor=”” : Change the text color of the menu item in the drawer.

Now we have some basic knowledge about DrawerLayout, Android NavigationView. so we are going to start the tutorial now.

Pre-requisite

You need some additional libraries/tools to complete this tutorial.
a. Toolbar: you need toolbar to sync it with NavigationView
b. Circle Image Library: This is optional. If you want to show circular image in header of NavigationView, add below gradle in app/build.gradle.

compile 'de.hdodenhof:circleimageview:2.0.0'

c. Material Design support library : Just add below gradle in app/build.gradle

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

1.1 Creating new project

Follow steps written below to create a new project.
a. Goto File –> New –> New Project. Then, Write application name as NavigationViewTutorial and click next.
b. Select Minimum SDK 15 or more –> click next –> Select Empty Activity –> click next –> click finish.
If you have followed above process correctly, you will get a newly created project successfully.

1.2 Add Gradle in app/build.gradle

Add following code in app/build.gradle file and click on Sync Now button(Will be shown just after you copy/paste this code into app/build.gradle).

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'

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

    // Gradle for circular image being shown in header of NavigationView.
    compile 'de.hdodenhof:circleimageview:2.0.0'

    // Gradle for support library.
    compile 'com.android.support:design:23.4.0'
}

1.3 Update Values Folder

Finally, your values folder would look like below. You just copy/paste these code into respective values folder so that you do not get error while following this tutorial.
colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#F44336</color>          //Changed from default.
    <color name="colorPrimaryDark">#D32F2F</color>      //Changed from default.
    <color name="colorAccent">#FF4081</color>
</resources>

dimens.xml

<resources>
    <dimen name="title_padding">8dp</dimen>
    <dimen name="title_text_size">28sp</dimen>
    <dimen name="text_size">14sp</dimen>
    <dimen name="padding_left">24dp</dimen>
    <dimen name="image_width">76dp</dimen>
    <dimen name="image_height">76dp</dimen>
    <dimen name="header_height">190dp</dimen>
    <dimen name="username_padding">4dp</dimen>
    <dimen name="email_padding">8dp</dimen>
</resources>

strings.xml

<resources>
    <string name="app_name">NavigationViewTutorial</string>
    <string name="closeDrawer">Navigation View Closed</string>
    <string name="openDrawer">Navigation View Opened</string>
    <string name="inbox">Inbox</string>
    <string name="starred">Starred</string>
    <string name="sent_mail">Sent mail</string>
    <string name="draft">Drafts</string>
    <string name="all_mail">All mails</string>
    <string name="trash">Trash</string>
    <string name="spam">Spams</string>
    <string name="sub_menu">Sub Menu</string>
    <string name="user_name">Rajeev kumar</string>
    <string name="email">tutorialwing@gmail.com</string>
    <string name="right_side_navigationview">Right Side NavigationView - add code
        to perform some actions on current content</string>
</resources>

values/styles.xml
Notice that parent is changed to Theme.AppCompat.Light.NoActionBar from default to use toolbar.

<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>
</resources>

values-v21/styles.xml
You will need to create values-v21 folder in res folder. Then, copy/paste below code into it. Notice that parent is changed to Theme.AppCompat.Light.NoActionBar from default to use toolbar. Also, We have added @android:color/transparent to make status bar transparent.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="android:colorPrimary">@color/colorPrimary</item>
        <item name="android:colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="android:statusBarColor">@android:color/transparent</item>
    </style>
</resources>



1.4 Creating toolbar

Note that we have already added Theme.AppCompat.Light.NoActionBar in styles.xml file. Now, we need to create a folder toolbar.xml in res folder. Then, copy/paste below code into it.

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="@dimen/abc_action_bar_default_height_material"
    android:background="@color/colorPrimary"
    app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>

To set toolbar as action bar, you need to get reference of the toolbar and set it as action bar in MainActivtiy.java.

public class MainActivity extends AppCompatActivity {

	private Toolbar toolbar;

	@Override

	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

		// Find the toolbar by id and set it as actionBar.

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

		setSupportActionBar(toolbar);

	}
}

1.5 Creating Layouts for NavigationView

As we already know that there are two main components in android NavigationView. They are –
a. HeaderView
b. Menu items.

We will create layout for these components now.

1.5.1 Creating Header layout

Create a file header.xml and copy/paste below code into it. This will create layout for header view in NavigationView. It will be shown in top part of the NavigationView. For now we are showing Profile image, username and email in it. Here, CircleImageView is used to show circular image in header view.

<?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="@dimen/header_height"
    android:background="@drawable/background"
    android:orientation="vertical">

    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/profile_image"
        android:layout_width="@dimen/image_width"
        android:layout_height="@dimen/image_height"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="@dimen/padding_left"
        android:src="@drawable/tutorialwing"/>

    <TextView
        android:id="@+id/username"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/email"
        android:layout_alignLeft="@+id/profile_image"
        android:layout_alignStart="@+id/profile_image"
        android:gravity="left"
        android:paddingBottom="@dimen/username_padding"
        android:text="@string/user_name"
        android:textColor="@android:color/white"
        android:textSize="@dimen/text_size"
        android:textStyle="bold"/>

    <TextView
        android:id="@+id/email"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/username"
        android:layout_alignParentBottom="true"
        android:layout_alignStart="@+id/username"
        android:layout_marginBottom="@dimen/email_padding"
        android:gravity="left"
        android:text="@string/email"
        android:textColor="@android:color/white"
        android:textSize="@dimen/text_size"/>

</RelativeLayout>

1.5.2 Creating Menu items layout

Now, we will create menu items for NavigationView. So, create a folder menu in res folder(res/menu). Then, create drawer.xml file and copy/paste below code into it.
a single < item … /> represents an item in NavigationView. Attributes used in < item .. /> are as below.
android:id=”” : id of the item
android:checked=”” : Set whether menu item is checked or unchecked
android:icon=”” : Set the icon to be shown to the left of menu item title
android:title=”” : Set the title of the menu item

A group represents a common type of the menu items. android:checkableBehavior=”single” represents that only one menu Item can be selected a time in this group.

<?xml version="1.0" encoding="utf-8"?>
<menu
    xmlns:android="http://schemas.android.com/apk/res/android">

    <group android:checkableBehavior="single">
        <item
            android:id="@+id/inbox"
            android:checked="false"
            android:icon="@drawable/ic_inbox"
            android:title="@string/inbox"/>
        <item
            android:id="@+id/starred"
            android:checked="false"
            android:icon="@drawable/ic_star"
            android:title="@string/starred"/>
        <item
            android:id="@+id/sent_mail"
            android:checked="false"
            android:icon="@drawable/ic_send"
            android:title="@string/sent_mail"/>
        <item
            android:id="@+id/drafts"
            android:checked="false"
            android:icon="@drawable/ic_drafts"
            android:title="@string/draft"/>

        <item android:title="@string/sub_menu">
            <menu>
                <group
                    android:id="@+id/nav_main_content"
                    android:checkableBehavior="single">
                    <item
                        android:id="@+id/allmail"
                        android:checked="false"
                        android:icon="@drawable/ic_email"
                        android:title="@string/all_mail"/>
                    <item
                        android:id="@+id/trash"
                        android:checked="false"
                        android:icon="@drawable/ic_delete"
                        android:title="@string/trash"/>
                    <item
                        android:id="@+id/spam"
                        android:checked="false"
                        android:icon="@drawable/ic_error"
                        android:title="@string/spam"/>
                </group>
            </menu>
        </item>

    </group>
</menu>

Note:
a. I have also created another type of menu items(drawer2.xml). For the sake of this post, I am not going to show this here. If you want to create another menu items, you may get it from source code.
b. Also, you will get the images used in this tutorial from source code. You can download the source code given at start of this tutorial.

1.6 Creating left and right NavigationView

After all setups, It’s time to create left and right navigation view. So, open activity_main.xml and add main content container and left or right navigation view in it. You just need to copy/paste below code into activity_main.xml.

<!-- DrawerLayout acting as top level container for the main screen. -->
<android.support.v4.widget.DrawerLayout
    android:id="@+id/drawer"
    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:fitsSystemWindows="true"
    tools:context=".MainActivity">

    <!-- Primary content-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <include
            android:id="@+id/toolbar"
            layout="@layout/toolbar"/>
        <FrameLayout
            android:id="@+id/frame"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
        </FrameLayout>
    </LinearLayout>

    <!-- Left side NavigationView -->
    <android.support.design.widget.NavigationView
        android:id="@+id/navigation_view_left"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:headerLayout="@layout/header"
        app:menu="@menu/drawer"/>

    <!-- Right side NavigationView -->
    <android.support.design.widget.NavigationView
        android:id="@+id/navigation_view_right"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="end">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center">
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:text="@string/right_side_navigationview"/>
        </LinearLayout>
    </android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>

Note:
a. Root layout is DrawerLayout that contains three child. first child is primary content, then, left NavigationView, then, right NavigationView.
b.android:layout_gravity=”” represents whether is left or right drawer.
c.app:headerLayout=”” represents the header layout.
d.app:menu=”@menu/drawer” represents the menu list being shown in the drawer.

Now, open MainActivity.java and perform below operations in it.
a. Get the reference to toolbar, set it as support action bar.
b. Get the reference to NavigationView and DrawerLayout and do required stuffs like adding drawerListener in drawerLayout etc. in it.

To do all the above operations, you just need to add below code into MainActivity.java.

package tutorialwing.com.navigationviewtutorial;


import android.os.Bundle;

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.support.v7.widget.Toolbar;

import android.view.View;



public class MainActivity extends AppCompatActivity {


	private Toolbar toolbar;

	private NavigationView navigationView;

	private DrawerLayout drawerLayout;


	@Override

	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_main);

	
	        // Find the toolbar by id and set it as actionBar.

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

		setSupportActionBar(toolbar);


		// Find the navigationView and DrawerLayout by their ids.

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

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


		setDrawerLayout();

	}


	private void setDrawerLayout() {

		ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout,
				toolbar, R.string.openDrawer, R.string.closeDrawer) {


			@Override

			public void onDrawerClosed(View drawerView) {

				// Write code to perform action when drawer is closed.

				super.onDrawerClosed(drawerView);

			}


			@Override

			public void onDrawerSlide(View drawerView, float slideOffset) {
	
			        // Write code to perform action when drawer is sliding.

				super.onDrawerSlide(drawerView, slideOffset);

			}


			@Override

			public void onDrawerOpened(View drawerView) {

				// Write code to perform action when drawer is opened.

				super.onDrawerOpened(drawerView);

			}

		};


		// Set the actionbarToggle to drawer layout.

		drawerLayout.addDrawerListener(actionBarDrawerToggle);


		// Calling sync state is necessary or else your hamburger icon wont show up.

		actionBarDrawerToggle.syncState();

	}

}

Now, if you run the app, you will see the left and right NavigationView.




2. Setting Item ClickListener in NavigationView

Till now we have successfully created left and right NavigationView. In this part, we will set menu item click listener. So, we are going to show a Fragment on click of any menu item with title as selected menu item title.

2.1 Creating Fragment to show on menu item click

Create a fragment with name SelectedFragment. Name the java class as SelectedFragment.java and xml file as fragment_selected.xml. Finally, both of these files would look like below.
SelectedFragment.java

package tutorialwing.com.navigationviewtutorial;

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

public class SelectedFragment extends Fragment {
	private String title;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_selected, container, false);
	}
	@Override
	public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		// Set selected fragment name.
		TextView txvTitle = (TextView) view.findViewById(R.id.title);
		txvTitle.setText(title);
	}
	public void setTitle(String title) {
		this.title = title;
	}
}

fragment_selected.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="match_parent"
    android:orientation="vertical">
    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:background="@color/colorPrimary"
        android:padding="@dimen/title_padding"
        android:textColor="@android:color/white"
        android:textSize="@dimen/title_text_size"/>
</RelativeLayout>

2.2 Add Code to perform item click into MainActivity.java

Open MainActivity.java and set setNavigationItemSelectedListener in NavigationView. Also, perform the required action in onNavigationItemSelected method. Here, we have performed following actions on menu item click.
a. Toggled the checked state of menuItem.
b. Closed the drawer.
c. Showed the SelectedFragment.
d. Showed a toast message to show selected menu item title.

// Set item click listener to perform action on menu item click.
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
	@Override
	public boolean onNavigationItemSelected(MenuItem menuItem) {
		// Toggle the checked state of menuItem.
		menuItem.setChecked(!menuItem.isChecked());
		// Close the drawer
		drawerLayout.closeDrawers();
		// Get the menu by Id and perform desired actions. Here, we are showing a common
		// fragment(SelectedFragment) on click of any menu item. You can do any action
		// on click of a menu item similarly. You just need to write code as below
		// case R.id.menu_item_id:
		// 		some action to perform
		// 		break;
		switch (menuItem.getItemId()) {
			case R.id.inbox:
			case R.id.starred:
			case R.id.sent_mail:
			case R.id.drafts:
			case R.id.allmail:
			case R.id.trash:
			case R.id.spam:
				SelectedFragment selectedFragment = new SelectedFragment();
				selectedFragment.setTitle(String.valueOf(menuItem.getTitle()));
				FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
				fragmentTransaction.replace(R.id.frame, selectedFragment);
				fragmentTransaction.commit();
				break;
		}

		Toast.makeText(getApplicationContext(), menuItem.getTitle() + " Selected", Toast.LENGTH_SHORT).show();
		return true;
	}
});

Final MainActivity.java code

package tutorialwing.com.navigationviewtutorial;

import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

	private Toolbar toolbar;
	private NavigationView navigationView;
	private DrawerLayout drawerLayout;

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

		// Find the toolbar by id and set it as actionBar.
		toolbar = (Toolbar) findViewById(R.id.toolbar);
		setSupportActionBar(toolbar);

		// Find the navigationView and DrawerLayout by their ids.
		navigationView = (NavigationView) findViewById(R.id.navigation_view_left);
		drawerLayout = (DrawerLayout) findViewById(R.id.drawer);

		setDrawerLayout();
		setItemSelectListener();
	}

	private void setDrawerLayout() {
		ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout,
				toolbar, R.string.openDrawer, R.string.closeDrawer) {

			@Override
			public void onDrawerClosed(View drawerView) {
				// Write code to perform action when drawer is closed.
				super.onDrawerClosed(drawerView);
			}

			@Override
			public void onDrawerSlide(View drawerView, float slideOffset) {
				// Write code to perform action when drawer is sliding.
				super.onDrawerSlide(drawerView, slideOffset);
			}

			@Override
			public void onDrawerOpened(View drawerView) {
				// Write code to perform action when drawer is opened.
				super.onDrawerOpened(drawerView);
			}
		};

		// Set the actionbarToggle to drawer layout.
		drawerLayout.addDrawerListener(actionBarDrawerToggle);

		// Calling sync state is necessary or else your hamburger icon wont show up.
		actionBarDrawerToggle.syncState();
	}

	private void setItemSelectListener() {
		if (navigationView == null)
			return;

		// Set item click listener to perform action on menu item click.
		navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {

			@Override
			public boolean onNavigationItemSelected(MenuItem menuItem) {

				// Toggle the checked state of menuItem.
				menuItem.setChecked(!menuItem.isChecked());

				// Close the drawer
				drawerLayout.closeDrawers();

				// Get the menu by Id and perform desired actions. Here, we are showing a common
				// fragment(SelectedFragment) on click of any menu item. You can do any action
				// on click of a menu item similarly. You just need to write code as below
				// case R.id.menu_item_id:
				// 		some action to perform
				// 		break;
				switch (menuItem.getItemId()) {
					case R.id.inbox:
					case R.id.starred:
					case R.id.sent_mail:
					case R.id.drafts:
					case R.id.allmail:
					case R.id.trash:
					case R.id.spam:
						SelectedFragment selectedFragment = new SelectedFragment();
						selectedFragment.setTitle(String.valueOf(menuItem.getTitle()));
						FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
						fragmentTransaction.replace(R.id.frame, selectedFragment);
						fragmentTransaction.commit();
						break;
				}

				Toast.makeText(getApplicationContext(), menuItem.getTitle() + " Selected", Toast.LENGTH_SHORT).show();
				return true;
			}
		});
	}
}



Output

If you will run the app at this point, you will get the output as shown above.

Conclusion

Android NavigationView is one the most popular android material design support library that helps in navigating through app. You can set left or right navigation view as per your need.

One Response

  1. Chrinstine August 9, 2016

Leave a Reply