# android navigation drawer

Lets start by creating new project for that&#x20;

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

![](https://111087263-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-L_Lt0fyRsHcS_4ZagFx%2F-LlfUD_Y5FdfYwMhLtXe%2F-LlfUPCIrYpwwnWp4F67%2Fdevice-2019-08-07-151720.png?alt=media\&token=1d3c3c30-bedf-40e7-9b81-32458570d15b)

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

![](https://111087263-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-L_Lt0fyRsHcS_4ZagFx%2F-LmESU9HlKnjz7nrWD_d%2F-LmEYZiNyZ4ZCecrxsqR%2Fnavigation_detail.png?alt=media\&token=b379163c-561e-4ca4-86f8-8b9ce90235b0)

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)

![](https://111087263-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-L_Lt0fyRsHcS_4ZagFx%2F-LmESU9HlKnjz7nrWD_d%2F-LmEbYE3GypQclq362z0%2FScreenshot_1565777585.png?alt=media\&token=284e4b67-4fdb-4fc0-91ea-54b1cb13ede4)

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

{% code title="side_navbar.xml" %}
```markup
<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>
```
{% endcode %}

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

```markup
<?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.

{% code title="NavigationDrawerActivity.java" %}
```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;
}
```
{% endcode %}

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

```markup
<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.

{% code title="NavigationDrawerActivity.java" %}
```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();
    }
});
```
{% endcode %}

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.

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

Final java code should look like below

{% code title="NavigationDrawerActivity.java" %}
```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;
    }

```
{% endcode %}

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!
