Android Navigation Drawer Example
Android Navigation Drawer Example
So first we will create a new project. I am using Android Studio. (No reason of using
eclipse nowdays )
Create a new project. I created NavigationDrawerExample.
Now when you are asked to select an activity from the template, select the navigation
drawer activity.
If you want to add Navigation Drawer Activity to your existing project you can simply
add it by going to your package -> right click -> new -> activity -> navigation drawer
activity
Adding Android Navigation Drawer Activity
Once your project is loaded your navigation drawer activity is ready. You can now run
your application.
Android Navigation Drawer Example
Pretty easy right? Yeah its quite easy. Now we will learn to customise the menus and to
add the screens for the menus using fragment.
Now you can change the menus given in the drawer to whatever you want. To change the
menu open the activity_main_drawer.xml inside menu folder. Here is
my activity_main_drawer.xml file I deleted the menus and now we have only 3 menus
(You can add as many as you want).
activity_main_drawer.xml
1 <?xml version="1.0" encoding="utf-8"?>
2 <menu xmlns:android="http://schemas.android.com/apk/res/android">
3
4 <group android:checkableBehavior="single">
5 <item
6 android:id="@+id/nav_menu1"
7 android:icon="@mipmap/ic_launcher"
9 <item
10 android:id="@+id/nav_menu2"
11 android:icon="@mipmap/ic_launcher"
13 <item
14 android:id="@+id/nav_menu3"
15 android:icon="@mipmap/ic_launcher"
17
18 </group>
19
20
21 </menu>
I changed the text to Menu 1, Menu 2 and Menu3 and for icons I used the default android
icon. You can use custom icons just paste the icon image inside drawer folder and you
can use them.
If you try to run app now it will give error, as we have changed the menu items and ids.
So first go inside MainActivity.java (or the java file for your navigation drawer
activity). And modify the overriden method onNavigationItemSelected(MenuItem
item) as follows.
Java
1 @SuppressWarnings("StatementWithEmptyBody")
2 @Override
5 int id = item.getItemId();
7 if (id == R.id.nav_menu1) {
10
12
13 }
15 drawer.closeDrawer(GravityCompat.START);
16 return true;
17 }
Here we removed the previous if else conditions and added our own according to the
customised menu ids.
You can also customise the navigation drawer header. For this you need to go to
the nav_header_main.xml file. I also changed this file as below.
nav_header_main.xml
2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3 android:layout_width="match_parent"
4 android:layout_height="@dimen/nav_header_height"
5 android:background="@color/colorPrimaryDark"
6 android:gravity="bottom"
7 android:orientation="vertical"
8 android:paddingBottom="@dimen/activity_vertical_margin"
9 android:paddingLeft="@dimen/activity_horizontal_margin"
10 android:paddingRight="@dimen/activity_horizontal_margin"
11 android:paddingTop="@dimen/activity_vertical_margin"
12 android:theme="@style/ThemeOverlay.AppCompat.Dark">
13
14
15 <TextView
16 android:layout_width="match_parent"
17 android:layout_height="wrap_content"
18 android:paddingTop="@dimen/nav_header_vertical_spacing"
20 android:textAppearance="?android:textAppearanceLarge" />
21
22 </LinearLayout>
You can see a circular red button in your activity. You can remove it if you do not need
it. To remove this button go to app_bar_main.xml inside the layout folder and remove
the floating button from there.
app_bar_main.xml
1 <?xml version="1.0" encoding="utf-8"?>
2 <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
3 xmlns:app="http://schemas.android.com/apk/res-auto"
4 xmlns:tools="http://schemas.android.com/tools"
5 android:layout_width="match_parent"
6 android:layout_height="match_parent"
7 android:fitsSystemWindows="true"
8 tools:context="net.simplifiedcoding.navigationdrawerexample.MainActivity">
10 <android.support.design.widget.AppBarLayout
11 android:layout_width="match_parent"
12 android:layout_height="wrap_content"
13 android:theme="@style/AppTheme.AppBarOverlay">
14
15 <android.support.v7.widget.Toolbar
16 android:id="@+id/toolbar"
17 android:layout_width="match_parent"
18 android:layout_height="?attr/actionBarSize"
19 android:background="?attr/colorPrimary"
20 app:popupTheme="@style/AppTheme.PopupOverlay" />
21
22 </android.support.design.widget.AppBarLayout>
23
25
26 </android.support.design.widget.CoordinatorLayout>
To remove the default Hello World text view go to the content_main.xml file.
As we have removed the button we also need to modify the code
inside onCreate() method of MainActivity.java so modify it as follow or you will get
error.
Java
1 @Override
3 super.onCreate(savedInstanceState);
4 setContentView(R.layout.activity_main);
6 toolbar.setTitle("Menu 1");
7 setSupportActionBar(toolbar);
10
14 drawer.setDrawerListener(toggle);
15 toggle.syncState();
16
18 navigationView.setNavigationItemSelectedListener(this);
19 }
Right click on layouts folder and create a new layout resource file. I named
it fragment_menu_1.xml, fragment_menu_2.xml and fragment_menu_3.xml. Write
the following xml code inside all these files.
fragment_menu_1
2 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
3 android:layout_width="match_parent"
4 android:layout_height="match_parent">
6 <TextView
7 android:layout_width="wrap_content"
8 android:layout_height="wrap_content"
9 android:textAppearance="?android:attr/textAppearanceLarge"
10 android:text="Menu 1"
11 android:id="@+id/textView"
12 android:layout_centerVertical="true"
13 android:layout_centerHorizontal="true" />
14
15 </RelativeLayout>
All the three files contains the same code only for the text I changed it to Menu 1, Menu
2 and Menu3 for the respective files.
You can design the screens according to your application requirement but for now I am
justing putting a normal TextView as it is an example demonstrating the concept only.
So we have the layouts now we will put these screens inside your activity using
fragments. For this we need a FrameLayout so go inside content_main.xml file and add
a FrameLayout.
content_main.xml
1 <?xml version="1.0" encoding="utf-8"?>
2 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
3 xmlns:app="http://schemas.android.com/apk/res-auto"
4 xmlns:tools="http://schemas.android.com/tools"
5 android:layout_width="match_parent"
6 android:layout_height="match_parent"
7 android:paddingBottom="@dimen/activity_vertical_margin"
8 android:paddingLeft="@dimen/activity_horizontal_margin"
9 android:paddingRight="@dimen/activity_horizontal_margin"
10 android:paddingTop="@dimen/activity_vertical_margin"
11 app:layout_behavior="@string/appbar_scrolling_view_behavior"
12 tools:context="net.simplifiedcoding.navigationdrawerexample.MainActivity"
13 tools:showIn="@layout/app_bar_main">
14
15
16 <FrameLayout
17 android:id="@+id/content_frame"
18 android:layout_width="match_parent"
19 android:layout_height="match_parent" />
20
21 </RelativeLayout>
Menu1.java
Java
1 package net.simplifiedcoding.navigationdrawerexample;
3 import android.os.Bundle;
4 import android.support.annotation.Nullable;
5 import android.support.v4.app.Fragment;
6 import android.view.LayoutInflater;
7 import android.view.View;
8 import android.view.ViewGroup;
10 /**
12 */
13
14
16
17 @Nullable
18 @Override
20 savedInstanceState) {
24 }
25
26
27 @Override
28 public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
29 super.onViewCreated(view, savedInstanceState);
30 //you can set the title for your toolbar here for different fragments different titles
31 getActivity().setTitle("Menu 1");
32 }
For the other two classes code will be the same, you only need to
change R.layout.fragment_menu_1 with the respective layout file for your fragment.
Java
1 @SuppressWarnings("StatementWithEmptyBody")
2 @Override
6 return true;
7 }
Now here we will create one more method named displaySelectedScreen(int itemId).
Java
7 switch (itemId) {
8 case R.id.nav_menu1:
10 break;
11 case R.id.nav_menu2:
13 break;
14 case R.id.nav_menu3:
16 break;
17 }
18
20 if (fragment != null) {
21 FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
22 ft.replace(R.id.content_frame, fragment);
23 ft.commit();
24 }
25
27 drawer.closeDrawer(GravityCompat.START);
28 }
We will call this method whenever a navigation menu item is selected. So inside
onNavigationItemSelected(MenuItem item) we need to add the following line.
Java
1 @SuppressWarnings("StatementWithEmptyBody")
2 @Override
6 displaySelectedScreen(item.getItemId());
8 return true;
9 }
Now when the activity is first loaded we will display Menu1. For this just add the
following line inside onCreate() method of MainActivity.java.
Java
1 @Override
3 super.onCreate(savedInstanceState);
4 setContentView(R.layout.activity_main);
6 setSupportActionBar(toolbar);
13 drawer.setDrawerListener(toggle);
14 toggle.syncState();
15
17 navigationView.setNavigationItemSelectedListener(this);
18
20 displaySelectedScreen(R.id.nav_menu1);
21 }
MainActivity.java
Java
1 package net.simplifiedcoding.navigationdrawerexample;
3 import android.os.Bundle;
4 import android.support.design.widget.FloatingActionButton;
5 import android.support.design.widget.Snackbar;
6 import android.support.v4.app.Fragment;
7 import android.support.v4.app.FragmentTransaction;
8 import android.view.View;
9 import android.support.design.widget.NavigationView;
10 import android.support.v4.view.GravityCompat;
11 import android.support.v4.widget.DrawerLayout;
12 import android.support.v7.app.ActionBarDrawerToggle;
13 import android.support.v7.app.AppCompatActivity;
14 import android.support.v7.widget.Toolbar;
15 import android.view.Menu;
16 import android.view.MenuItem;
17
19 implements NavigationView.OnNavigationItemSelectedListener {
20
21 @Override
23 super.onCreate(savedInstanceState);
24 setContentView(R.layout.activity_main);
26 setSupportActionBar(toolbar);
27
28
29
33 drawer.setDrawerListener(toggle);
34 toggle.syncState();
35
37 navigationView.setNavigationItemSelectedListener(this);
38
40 displaySelectedScreen(R.id.nav_menu1);
41 }
42
43 @Override
46 if (drawer.isDrawerOpen(GravityCompat.START)) {
47 drawer.closeDrawer(GravityCompat.START);
48 } else {
49 super.onBackPressed();
50 }
51 }
52
53 @Override
55 // Inflate the menu; this adds items to the action bar if it is present.
56 getMenuInflater().inflate(R.menu.main, menu);
57 return true;
58 }
59
60 @Override
62 // Handle action bar item clicks here. The action bar will
65 int id = item.getItemId();
66
67 //noinspection SimplifiableIfStatement
68 if (id == R.id.action_settings) {
69 return true;
70 }
71
72 return super.onOptionsItemSelected(item);
73 }
74
75 private void displaySelectedScreen(int itemId) {
76
79
81 switch (itemId) {
82 case R.id.nav_menu1:
84 break;
85 case R.id.nav_menu2:
87 break;
88 case R.id.nav_menu3:
90 break;
91 }
92
94 if (fragment != null) {
95 FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
96 ft.replace(R.id.content_frame, fragment);
97 ft.commit();
98 }
99
101 drawer.closeDrawer(GravityCompat.START);
102 }
103
104
105 @SuppressWarnings("StatementWithEmptyBody")
106 @Override
108
109 //calling the method displayselectedscreen and passing the id of selected menu
110 displaySelectedScreen(item.getItemId());
113 }
114
115
116 }
Bingo! Its working absolutely fine. If you are having troubles you can get the source code
from the below github repository.