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