NavigationView: Material Design: Android Design Support Library

Step 1: Create a menu for navigation drawer items
upport-library/">Android Design Support library. If you don’t know then let me tell you that this is the third post regarding Android material design and, today we are going to talk about NavigationView

In the previous two parts, we learned about Floating action Button(FAB) and android Snakebar, and today’s our topic is android NavigationView

Android Design Support Library: NavigationView

When Google announced material design, we don’t have this much huge repository of components and tools, So developers like us were dependent on the third party tools and libraries, But thank god, with the release of Android design support library it’s very easy to implement Navigation drawer in any android application.

You surely know a headache of implementing navigation drawer before android design support library. But Now it’s like the knife in the cake let me explain how. I will tell you directly about NavigationView, which is the amazing component of the material design.

How does NavigationView work?

Before NavigationView, we were dependent on either linearLayout or ListView by defining a custom adapter for showing navigation drawer as per our need. But with NavigationView we can directly include it inside the same DrawerLayout.

Two important parameters

Here we are discussing two main essential parameters which are must require for set up NavigationView, Same as the navigation drawer in the inbox and Google Play Store applications.

app:menu – You can add a list of navigation drawer items, here we are going to create one normal menu file for the needed details.

app:headerlayout – which is header layout, like we Display profile picture and background image with the name and other items.

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

Here are 2 ways we can implement a NavigationView, I am going to show you both the ways.

  1. Design time, by preparing menu file with the items

  2. Run time, by adding details into the Navigation view programmatically

Now, Let’s begin to code…

Design time:

strong>Step 1: Create a menu for navigation drawer items

It can be created same as a menu xml file(drawer_view.xml), just make sure you create under the menu folder

<menu xmlns:android="http://schemas.android.com/apk/res/android">
 
    <group android:checkableBehavior="single">
        <item
            android:id="@+id/nav_home"
            android:icon="@drawable/ic_drawer_home"
            android:title="@string/nav_home" />
        <item
            android:id="@+id/nav_about"
            android:icon="@drawable/ic_drawer_about"
            android:title="@string/nav_about" />
        <item
            android:id="@+id/nav_settings"
            android:icon="@drawable/ic_drawer_settings"
            android:title="@string/nav_settings" />
 
        <item
            android:id="@+id/navigation_subheader"
            android:title="@string/nav_sub_header">
            <menu>
                <item
                    android:id="@+id/navigation_sub_item_1"
                    android:icon="@drawable/ic_drawer_about"
                    android:title="@string/nav_sub_item_1" />
                <item
                    android:id="@+id/navigation_sub_item_2"
                    android:icon="@drawable/ic_drawer_home"
                    android:title="@string/nav_sub_item_2" />
            </menu>
        </item>
    </group>
</menu>
Checkable menu items
u also can define the checkable behavior for each and every menu items using android:checkable attribute in the element, also for entire group with the android:checkableBehavior attribute in the element

  • single– Only one item can be checked (radio buttons)
  • all– More than one items or All items can be checked (checkboxes)
  • none– Not even single items are checkable
St
Step 2: Create a header layout
reate a header layout (drawer_header.xml) in layout folder.

<?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="192dp"
    android:background="?attr/colorPrimaryDark"
    android:padding="16dp"
    android:theme="@style/ThemeOverlay.AppCompat.Dark"
    android:orientation="vertical"
    android:gravity="bottom">
 
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Username"
        android:textAppearance="@style/TextAppearance.AppCompat.Body1"/>
</LinearLayout>
St
Step 3: Get NavigationView and include menu and header layout
strong>activity_main.xml
layout file & include NavigationView including Header and menu Layout attributes.

<?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"
    android:id="@+id/drawer_layout"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:fitsSystemWindows="true">
 
    <!-- Your content layout goes here -->
 
    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_height="match_parent"
        android:layout_width="wrap_content"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_drawer_header"
        app:menu="@menu/nav_drawer_view"/>
 
</android.support.v4.widget.DrawerLayout>
St
Step 4: Initialize Navigation view in activity class
nlighterJSRAW" data-enlighter-language="html">private NavigationView mNavigationView; mNavigationView = (NavigationView) findViewById(R.id.navigation_view);
St
Step 5: Assign navigation drawer item selected listener
nlighterJSRAW" data-enlighter-language="java">//setting up selected item listener navigationView.setNavigationItemSelectedListener( new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(MenuItem menuItem) { menuItem.setChecked(true); mDrawerLayout.closeDrawers(); return true; } });

Cr

Creating Navigation view By Programming

ted to add items in the NavigationView by programming then you can get a Menu object using getMenu() method of NavigationView so we can add items using Menu Object.

final Menu menu = navigationView.getMenu();
for (int i = 1; i <= 3; i++) {
    menu.add("Runtime item "+ i);
}

You can also add subsection or items by using SubMenu

// adding a section and items into it
final SubMenu subMenu = menu.addSubMenu("SubMenu Title");
for (int i = 1; i <= 2; i++) {
    subMenu.add("SubMenu Item " + i);
}

As we have already had added items into the drawer adapter, you need to refresh the adapter using below code:

for (int i = 0, count = mNavigationView.getChildCount(); i < count; i++) {
    final View child = mNavigationView.getChildAt(i);
    if (child != null && child instanceof ListView) {
        final ListView menuView = (ListView) child;
        final HeaderViewListAdapter adapter = (HeaderViewListAdapter) menuView.getAdapter();
        final BaseAdapter wrapped = (BaseAdapter) adapter.getWrappedAdapter();
        wrapped.notifyDataSetChanged();
    }
}

Ot

Other Points:

ou want to listen to the drawer open and close event, then you can use our former ActionBarDrawerToggle but of V7 support library.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
 
final ActionBar ab = getSupportActionBar();
ab.setHomeAsUpIndicator(R.drawable.ic_menu);
ab.setDisplayHomeAsUpEnabled(true);
  • Handle menu icon click event
@Override
public boolean onOptionsItemSelected(MenuItem item) {
 
    int id = item.getItemId();
 
    switch (id) {
 
        case android.R.id.home:
            mDrawerLayout.openDrawer(GravityCompat.START);
            return true;
 
        case R.id.action_settings:
            return true;
    }
 
    return super.onOptionsItemSelected(item);
}
  • And use No action bar theme
<style name="AppTheme" parent="Base.Theme.DesignDemo">
</style>
 
<style name="Base.Theme.DesignDemo" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">#2196F3</item>
    <item name="colorPrimaryDark">#1976D2</item>
    <item name="colorAccent">#E040FB</item>
    <item name="android:windowBackground">@color/window_background</item>
</style>
  • Handle back key press event
@Override
 public void onBackPressed() {
     if (isNavDrawerOpen()) {
         closeNavDrawer();
     } else {
         super.onBackPressed();
     }
 }
 
 protected boolean isNavDrawerOpen() {
     return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(GravityCompat.START);
 }
 
 protected void closeNavDrawer() {
     if (mDrawerLayout != null) {
         mDrawerLayout.closeDrawer(GravityCompat.START);
     }
 }

That’s it i think i almost cover everything but, you can always ask anything is missing in the comment section. till now we have learn about FAB(Floating Action Button), SnakeBar and navigationView. if you need to know for anything else you can surely write that to us.