navigation drawer android

Android Navigation Drawer Example[Latest]

Navigation Drawer slides in from the left and contains the navigation destinations for your app. Navigation drawer introduced with Android Support Library. I am going to use Android Studio templates for Navigation Drawer.

Please check Navigation Drawer Design Specifications.

I have explained the navigation drawer in three different parts,

  1. Navigation Drawer with Toolbar / Actionbar
  2. Navigation Drawer without Toolbar / Actionbar

Related Post

Android Bottom Navigation Material Design with Example [Updated]

Android Snackbar Material design with Example [Step By Step]


Navigation Drawer with Toolbar

Step 1 – Create Android Studio Project

Open Your Android Studio,

Create new Project And Select Navigation Drawer Activity Template,

Create new navigation drawer project

It will create App With Navigation Drawer And Navigation menus.

Default navigation drawer project screen

Step 2 – Navigation Drawer support Library

Navigation drawer support library added in android design support library,

implementation 'com.android.support:design:26.1.0'

Step 3 – Adding the Toolbar

Enable the toolbar by calling setSupportActionBar() by passing the toolbar object.

<android.support.v7.widget.Toolbar 
android:id="@+id/toolbar" 
android:layout_width="match_parent" 
android:layout_height="?attr/actionBarSize" 
android:background="?attr/colorPrimary" app:popupTheme="@style/AppTheme.PopupOverlay" />
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar);

Step 4 – Setup DrawerLayout

In Android, DrawerLayout acts as a top-level container for window content that allows for interactive “drawer” views to be pulled out from one or both vertical edges of the window. Drawer position and layout is controlled by using the layout_gravity attribute on child views corresponding to which side of view we want the drawer to emerge from like left to right.

<?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"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

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

</android.support.v4.widget.DrawerLayout>
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
        this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();

ActionBarDrawerToggle: This is used with a DrawerLayout to implement the recommended functionality of Navigation Drawers. It has the following usages:

  • Acts as a listener, for opening and closing of drawers.
  • Provides the hamburger icons in the ToolBar/ActionBar.
  • It allows for the animation between the hamburger icon and the arrow to exist.

addDrawerListener(toggle): This listener is used to keep notified of drawer events.

syncState(): will synchronize the icon’s state and display the hamburger icon or back arrow depending on whether the drawer is closed or open. Omitting this line of code won’t change the back arrow to the hamburger icon when the drawer is closed.

Important Methods Of Drawer Layout

closeDrawer(int gravity): Close the drawer view by animating it into view. We can close a drawer by passing END gravity to this method.

closeDrawers(): Close all the currently open drawer views by animating them out of view. We mainly use this method on click of any item of Navigation View.

isDrawerOpen(int drawerGravity): Used to check the drawer view is currently open or not. It returns true if the drawer view is open otherwise it returns false.

isDrawerVisible(int drawerGravity): Used to check the drawer view is currently visible on screen or not. It returns true if the drawer view is visible otherwise it returns false.

openDrawer(int gravity): Open the drawer view by animating it into view. We can open a Drawer by passing START gravity to this method.

Step 5 – Setup Navigation View

NavigationView is a better and easier to implement an alternative to a Navigation Drawer.

In Android, Navigation View represents a standard navigation menu for our application. The menu contents can be populated by a menu resource file.

<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="@layout/nav_header_main"
app:menu="@menu/activity_main_drawer" />
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);

The NavigationView essentially consists of two major components

app:headerLayout

Navigationview header

This View is typically displayed at the top of the Navigation Drawer. It essentially holds the profile picture, name email address, and a background cover pic. This view is defined in a separate layout file that we’ll look at in a bit.

app:menu

Navigationview menu

This is displayed below the HeaderView and it contains all the navigation items in the form of a list. The layout file for this is defined in the menus folder.

Important Methods Of Navigation View

Let’s we discuss some important methods of Navigation View that may be called in order to manage the Navigation View.

1.setNavigationItemSelectedListener(NavigationView.OnNavigationItemSelectedListener listener): This method is used to set a listener that will be notified when a menu item is selected.

Selecting Fragment For the Navigation Item

The MainActivity implements NavigationView.OnNavigationItemSelectedListener and override the onNavigationItemSelected(MenuItem item).By using the MenuItem Id we can able to launch the correct Fragment.

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();
    Fragment fragment = null;
    FragmentManager fragmentManager = getSupportFragmentManager();
    if (id == R.id.nav_camera) {
       fragment = new ImportFragment();
    } else if (id == R.id.nav_gallery) {
        fragment = new GalleryFragment();
    } 
    fragmentManager.beginTransaction().replace(R.id.frameLayout, fragment).commit();
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

Display The Default Fragment

In the OnCreate()  By default, we need to display the default Fragment. For that, we need to use

navigationView.setCheckedItem(R.id.nav_camera);

And Also need to start the fragment for the same,

FragmentManager fragmentManager = getSupportFragmentManager();
ImportFragment fragment = new ImportFragment();
fragmentManager.beginTransaction().replace(R.id.frameLayout, fragment).commit();

Final MainActivity.java

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

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

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        navigationView.setCheckedItem(R.id.nav_camera);

        FragmentManager fragmentManager = getSupportFragmentManager();
        ImportFragment fragment = new ImportFragment();
        fragmentManager.beginTransaction().replace(R.id.frameLayout, fragment).commit();
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.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();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        Fragment fragment = null;
        FragmentManager fragmentManager = getSupportFragmentManager();

        if (id == R.id.nav_camera) {
           fragment = new ImportFragment();
        } else if (id == R.id.nav_gallery) {
            fragment = new GalleryFragment();
        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }
        fragmentManager.beginTransaction().replace(R.id.frameLayout, fragment).commit();
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}

Navigation Drawer without Toolbar / Actionbar

Above, we have the example to create the navigation drawer with the toolbar. From that, we need to remove the toolbar layout and supportActionbar to create navigation drawer without Toolbar / Actionbar.

Delete AppBarLayout from your app_bar_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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"
    tools:context="com.example.velmurugan.navigationdrawerexample.MainActivity">

   <!-- <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways|snap"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>-->

    <include layout="@layout/content_main" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>

delete Toolbar from your MainActivity.java

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

Now you can see that Toolbar gone invisible.

navigation drawer without toolbar
velmm download code
github

1 thought on - Android Navigation Drawer Example[Latest]

  • Good Tutorial, very simple and easy to understand !

Leave a Reply

Your email address will not be published. Required fields are marked *