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

 

 

Showing Sliding Menu Using Navigation Drawer Android Tutorial

Nowadays, Lot of application’s use sliding menu to show the major functionality of their application.Applications like facebook, youtube, Gmail use sliding to navigate between major options. Now this sliding menu in android is done with the use of Navigation Drawer.

So, Let’s and add sliding menu to the application:-

Will need the following to implement Sliding Menu

1.I will have MainActivity containg drawerlayout in xml.

2.I will have one Listview for Sliding Menu items.

3. Adapter class to be bind to listview i will be using simple layout for adapter containg textview however you can customize according to your needs like adding image also.

So, Let’s Start by creating the project:-

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

2.Open strings.xml under res->values->strings.xml or create one if you not find and define items for sliding  menu

strings.xml

<!-- Navigation Drawer Menu Items -->
    <string-array name="nav_drawer_items">
        <item >Home</item>
        <item >Colleges and Universities</item>
        <item >Sports and Culture</item>
        <item >Tourism</item>
        <item >Explore Districts</item>
        <item >Explore DistrictMap</item>
        <item >Disclaimer</item>
    </string-array>

3.Create a layout for your Activity containing Navigation Drawer

activity_main.xml

<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- Framelayout to display Fragments -->
    <FrameLayout
        android:id="@+id/frame_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <!-- Listview to display Navigation Drawer items -->
    <ListView
        android:id="@+id/list_slidermenu"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:choiceMode="singleChoice"
        android:background="#33CCCC"
       />
</android.support.v4.widget.DrawerLayout>

4.Now Create a layout for your Adapter which will be set to ListView inside Navigation Drawer

drawer_list_item.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="fill_parent"
        android:layout_height="fill_parent"
        android:textSize="20dp"
        android:padding="5dp"
        />

</LinearLayout>

5. Now Define your Adapter class

NavDrawerListAdapter.java

package com.coderzpassion.punjab.explorepunjab;

import android.app.Activity;
import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

/**
 * Created by apple on 20/02/16.
 */public class NavDrawerListAdapter extends BaseAdapter {

    private Context context;
    private String [] navDrawerItems;

    public NavDrawerListAdapter(Context context, String [] navDrawerItems){
        this.context = context;
        this.navDrawerItems = navDrawerItems;
    }

    @Override
    public int getCount() {
        return navDrawerItems.length;
    }

    @Override
    public Object getItem(int position) {
        return navDrawerItems[position];
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            LayoutInflater mInflater = (LayoutInflater)
                    context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
            convertView = mInflater.inflate(R.layout.drawer_list_item, null);
        }


        TextView txtTitle = (TextView) convertView.findViewById(R.id.title);
      
        txtTitle.setTypeface(Typeface.createFromAsset(context.getAssets(), "Personal_Use.ttf"));
        txtTitle.setText(navDrawerItems[position]);

        return convertView;
    }

}

setting the background of action bar

final android.support.v7.app.ActionBar ab=getSupportActionBar();
        // setting the background color
        ab.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#33CCCC")));

setting custom view for Action Bar

//setting custom view for Action Bar
       getSupportActionBar().setCustomView(R.layout.action_bar_layout);

handling the click of Sliding menu Items

mDrawerList.setOnItemClickListener(new SlidingMenuClickListener());

private class SlidingMenuClickListener implements
            ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {
            // display view for selected nav drawer item
            displayView(position);
        }
    }

    /**
     * Diplaying fragment view for selected nav drawer list item
     * */
    private void displayView(int position) {
        // update the main content by replacing fragments
        Fragment fragment = null;
        switch (position) {
            case 0:
                fragment = AboutPunjab.newInstance("Punjab.html");

                break;
            case 1:
                fragment = AboutPunjab.newInstance("universities.html");
                break;
            case 2:
                fragment = AboutPunjab.newInstance("sportsandculture.html");
                break;
            case 3:
                fragment = AboutPunjab.newInstance("tourism.html");
                break;
            case 4:
                fragment = ExploreDistricts.newInstance("Punjab.html");
                break;
            case 5:
                fragment = ExploreMaps.newInstance("Punjab.html");
                break;
            case 6:
                fragment = AboutPunjab.newInstance("disclaimer.html");
                break;

            default:
                break;
        }

6. Now Create MainActivity.java and code for NavigationDrawer 

MainActivity.java

package com.coderzpassion.punjab.explorepunjab;

import android.app.Fragment;
import android.app.FragmentManager;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

public class MainActivity extends AppCompatActivity {

    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;

    // nav drawer title
    private CharSequence mDrawerTitle;

    // used to store app title
    private CharSequence mTitle;

    // slide menu items
    private String[] navMenuTitles;
    private TypedArray navMenuIcons;

   // private ArrayList<NavDrawerItem> navDrawerItems;
    private NavDrawerListAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);
        mTitle = mDrawerTitle = getTitle();
        navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
        mDrawerList.setOnItemClickListener(new SlidingMenuClickListener());

        // setting the nav drawer list adapter
        adapter = new NavDrawerListAdapter(getApplicationContext(),navMenuTitles);
        mDrawerList.setAdapter(adapter);
        // getting actionbar
        final android.support.v7.app.ActionBar ab=getSupportActionBar();
        // setting the background color
        ab.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#33CCCC")));
       

        // enabling action bar app icon and behaving it as toggle button
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayShowCustomEnabled(true);
        //setting custom view for Action Bar
        getSupportActionBar().setCustomView(R.layout.action_bar_layout);


        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,R.drawable.menu,
                 //nav menu toggle icon
                R.string.app_name, // nav drawer open - description for accessibility
                R.string.app_name // nav drawer close - description for accessibility
        ){
            public void onDrawerClosed(View view) {
                getSupportActionBar().setTitle(mTitle);
                // calling onPrepareOptionsMenu() to show action bar icons
                invalidateOptionsMenu();
            }

            public void onDrawerOpened(View drawerView) {
                getSupportActionBar().setTitle(mDrawerTitle);
                // calling onPrepareOptionsMenu() to hide action bar icons
                invalidateOptionsMenu();
            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        if (savedInstanceState == null) {
            // on first time display view for first nav item
            displayView(0);
        }


    }

    @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.
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement


        return super.onOptionsItemSelected(item);
    }

    private class SlidingMenuClickListener implements
            ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {
            // display view for selected nav drawer item
            displayView(position);
        }
    }

    /**
     * Diplaying fragment view for selected nav drawer list item
     * */
    private void displayView(int position) {
        // update the main content by replacing fragments
        Fragment fragment = null;
        switch (position) {
            case 0:
                fragment = AboutPunjab.newInstance("Punjab.html");

                break;
            case 1:
                fragment = AboutPunjab.newInstance("universities.html");
                break;
            case 2:
                fragment = AboutPunjab.newInstance("sportsandculture.html");
                break;
            case 3:
                fragment = AboutPunjab.newInstance("tourism.html");
                break;
            case 4:
                fragment = ExploreDistricts.newInstance("Punjab.html");
                break;
            case 5:
                fragment = ExploreMaps.newInstance("Punjab.html");
                break;
            case 6:
                fragment = AboutPunjab.newInstance("disclaimer.html");
                break;

            default:
                break;
        }

        if (fragment != null) {
            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction()
                    .replace(R.id.frame_container, fragment).commit();

            // update selected item and title, then close the drawer
            mDrawerList.setItemChecked(position, true);
            mDrawerList.setSelection(position);
            //setting the title according to navMenuitem
            mTitle=navMenuTitles[position];
            mDrawerLayout.closeDrawer(mDrawerList);
        } else {
            // error in creating fragment
            Log.e("MainActivity", "Error in creating fragment");
        }
    }
    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggls
        mDrawerToggle.onConfigurationChanged(newConfig);
    }
}

7.Creating Fragment to show when Clicking on Sliding Menu Item’s

AboutPunjab.java

package com.coderzpassion.punjab.explorepunjab;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;

import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;

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

    String title="";

    public AboutPunjab()
    {

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

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

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

        View rootView = inflater.inflate(R.layout.allfragments, container, false);
        WebView webView =(WebView)rootView.findViewById(R.id.mainwebview);
        webView.loadUrl("file:///android_asset/"+title);
     
    
        return rootView;
    }
}

8. layout for Fragment

allfragments.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
<WebView
    android:id="@+id/mainwebview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_above="@+id/adView"></WebView>
   
</RelativeLayout>

Output

slidingmenu