android navigation drawer

Lets start by creating new project for that

select file->new->new project

then give project a name, By default this will be used as app name and dont worry you can change it later

Im giving it name NavigationProject you can give any name you like

then click on empty activity and click finish to complete creating the project. Now you have successfully created project.

If you run the project you should get a similar view

Now you are landed on default activity which is mainactivity file which we dont need so we are going to create new activity which is navigation activity and set it as our launching activity.For that navigate to file -> new -> activity -> navigation activity also remember to set it to launcher activity. Click on finish. After gradle build is finished, go to android manifest file and delete the intent filter tag from mainactivity so that it wont launch for the first time when the app is opened.

now you may have noticed that we have multiple files created by android studio. we got,

  1. NavigationActivity.java(Activity file)

  2. activity_navigation.xml(layout file)

  3. content_navigation.xml

  4. app_bar_navigation.xml

  5. nav_header_navigation.xml

Now you may wonder why we need so many files to create a simple navigation drawer. You will find out soon after you follow my instructions.

Now if you run the app you will get screen similar to this

Now Im going to remove the floating action button on the bottom right side. Since we dont need it.

Sow now lets change the data in navigation drawer content like the profile image,name and email

To change data simply navigate to nav_header_navigation_drawer.xml and change text values and default image.

I have changed the text color to white and changed the default image with a avatar image (You can find lots of images from flaticon.com)

Now lets change the green gradient drawable in background.

Navigate to res->drawable->side_nav_bar.xml

remove the center color attribute and change the start and endcolor to your desire..(need some good gradients? head to uigradients website!!).

final code for gradient file will be something like this

side_navbar.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient
        android:angle="135"
        android:endColor="#6200EA"
        android:startColor="#AA00FF"
        android:type="linear" />
</shape>

So now we have made our app visually appeal to the users with navigation drawer. But thats not all you have to implement click functions for user to interact with your app. So lets start by interacting with the elements in navigation drawer. For the sake of making this tutorial as small as possible, Im going to remove all menu items except one. You have to edit activity_navigation_drawer_drawer.xml file inside menu folder. final code will be as below

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

    <group android:checkableBehavior="single">
        <item
            android:id="@+id/nav_home"
            android:icon="@drawable/ic_menu_camera"
            android:title="@string/menu_home" />
    </group>

</menu>

Now If you build the app you will get an error because we are referring these deleted menu items in the java file which is NavigationActivity.java

The onNavigationItemSelected method in this file should be like this.

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

    if (id == R.id.nav_home) {
        Toast.makeText(this,"clicked home",Toast.LENGTH_SHORT).show();
    } 

    DrawerLayout drawer = findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

When the home button is clicked it will show the toast message.You could add an intent other than toast to navigate to another activity on button click.

We will remove floating action button since we no longer need it.

remove this code snippet from app_bar_navigation_drawer.xml

<com.google.android.material.floatingactionbutton.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" />

Also we need to remove its reference in java file. Remove below code from onCreate method.

NavigationDrawerActivity.java
FloatingActionButton fab = 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();
    }
});

Now you are good to go you shouldnt see any error if so dont be scared to ask in comments below. Will also implement click events for menu item. You can see any empty if method in onOptionsItemSelected method. Simply add code inside the if condition so Im adding a simple toast.

NavigationDrawerActivity.java
if (id == R.id.action_settings) {
    Toast.makeText(this, "Clicked settings", Toast.LENGTH_SHORT).show();
    return true;
}

Final java code should look like below

NavigationDrawerActivity.java
package com.techpakka.navigationdrawer;

import android.os.Bundle;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;

import android.view.View;

import androidx.core.view.GravityCompat;
import androidx.appcompat.app.ActionBarDrawerToggle;

import android.view.MenuItem;

import com.google.android.material.navigation.NavigationView;

import androidx.drawerlayout.widget.DrawerLayout;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.view.Menu;
import android.widget.Toast;

public class NavigationDrawerActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_navigation_drawer);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        FloatingActionButton fab = 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 = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();
        navigationView.setNavigationItemSelectedListener(this);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = 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.navigation_drawer, 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) {
            Toast.makeText(this, "Clicked settings", Toast.LENGTH_SHORT).show();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

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

        if (id == R.id.nav_home) {
            Toast.makeText(this,"clicked home",Toast.LENGTH_SHORT).show();
        }

        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

If you want to customize navigation drawer further more like loading profile image and details to drawer from server, Stay tuned I will be adding a tutorial soon. Happy coding!

Last updated