You are on page 1of 21

Android Navigation Drawer Example

Creating a new project

 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.

Navigation Drawer Activity

Adding 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.

Customising Navigation Drawer Menus

 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"

8 android:title="Menu 1" />

9 <item

10 android:id="@+id/nav_menu2"

11 android:icon="@mipmap/ic_launcher"

12 android:title="Menu 2" />

13 <item

14 android:id="@+id/nav_menu3"

15 android:icon="@mipmap/ic_launcher"

16 android:title="Menu 3" />

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

3 public boolean onNavigationItemSelected(MenuItem item) {


4 // Handle navigation view item clicks here.

5 int id = item.getItemId();

7 if (id == R.id.nav_menu1) {

8 // Handle the camera action

9 } else if (id == R.id.nav_menu2) {

10

11 } else if (id == R.id.nav_menu3) {

12

13 }

14 DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);

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

1 <?xml version="1.0" encoding="utf-8"?>

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"

19 android:text="Navigation Drawer Example"

20 android:textAppearance="?android:textAppearanceLarge" />

21

22 </LinearLayout>

 Now you can run your application.


Android Navigation Drawer Example

Removing the Floating Action Button

 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

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

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

2 protected void onCreate(Bundle savedInstanceState) {

3 super.onCreate(savedInstanceState);

4 setContentView(R.layout.activity_main);

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

6 toolbar.setTitle("Menu 1");

7 setSupportActionBar(toolbar);

10

11 DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);

12 ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(

13 this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);

14 drawer.setDrawerListener(toggle);

15 toggle.syncState();

16

17 NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);

18 navigationView.setNavigationItemSelectedListener(this);

19 }

 Now we will create fragments for our navigation menus.

Creating Screens for Navigation Menus using Fragment


Now whenever we click on a navigation item from the drawer a respective screen should open,
for this we will use fragments. As we have three navigation menus we will create three layouts
inside our layout folder.

 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

1 <?xml version="1.0" encoding="utf-8"?>

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>

 Now we will create the Fragments.


 So create 3 java classes inside your package named Menu1, Menu2 and Menu3 and write
the following code.

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 /**

11 * Created by Belal on 18/09/16.

12 */

13

14

15 public class Menu1 extends Fragment {

16

17 @Nullable

18 @Override

19 public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle

20 savedInstanceState) {

21 //returning our layout file

22 //change R.layout.yourlayoutfilename for each of your fragments

23 return inflater.inflate(R.layout.fragment_menu_1, container, false);

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.

Switching Between Fragments on Navigation Drawer Menu Selection

 Now come inside MainActivity.java and empty the


method onNavigationItemSelected(MenuItem item) as follows.

Java

1 @SuppressWarnings("StatementWithEmptyBody")

2 @Override

3 public boolean onNavigationItemSelected(MenuItem item) {

5 //make this method blank

6 return true;

7 }

 Now here we will create one more method named displaySelectedScreen(int itemId).

Java

1 private void displaySelectedScreen(int itemId) {


2

3 //creating fragment object

4 Fragment fragment = null;

6 //initializing the fragment object which is selected

7 switch (itemId) {

8 case R.id.nav_menu1:

9 fragment = new Menu1();

10 break;

11 case R.id.nav_menu2:

12 fragment = new Menu2();

13 break;

14 case R.id.nav_menu3:

15 fragment = new Menu3();

16 break;

17 }

18

19 //replacing the fragment

20 if (fragment != null) {

21 FragmentTransaction ft = getSupportFragmentManager().beginTransaction();

22 ft.replace(R.id.content_frame, fragment);

23 ft.commit();

24 }

25

26 DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);

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

3 public boolean onNavigationItemSelected(MenuItem item) {

5 //calling the method displayselectedscreen and passing the id of selected menu

6 displaySelectedScreen(item.getItemId());

7 //make this method blank

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

2 protected void onCreate(Bundle savedInstanceState) {

3 super.onCreate(savedInstanceState);

4 setContentView(R.layout.activity_main);

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

6 setSupportActionBar(toolbar);

10 DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);

11 ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(


12 this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);

13 drawer.setDrawerListener(toggle);

14 toggle.syncState();

15

16 NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);

17 navigationView.setNavigationItemSelectedListener(this);

18

19 //add this line to display menu1 when the activity is loaded

20 displaySelectedScreen(R.id.nav_menu1);

21 }

 So the final code for MainActivity.java is.

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

18 public class MainActivity extends AppCompatActivity

19 implements NavigationView.OnNavigationItemSelectedListener {

20

21 @Override

22 protected void onCreate(Bundle savedInstanceState) {

23 super.onCreate(savedInstanceState);

24 setContentView(R.layout.activity_main);

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

26 setSupportActionBar(toolbar);

27

28

29

30 DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);

31 ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(

32 this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);

33 drawer.setDrawerListener(toggle);

34 toggle.syncState();

35

36 NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);

37 navigationView.setNavigationItemSelectedListener(this);

38

39 //add this line to display menu1 when the activity is loaded

40 displaySelectedScreen(R.id.nav_menu1);

41 }

42

43 @Override

44 public void onBackPressed() {


45 DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);

46 if (drawer.isDrawerOpen(GravityCompat.START)) {

47 drawer.closeDrawer(GravityCompat.START);

48 } else {

49 super.onBackPressed();

50 }

51 }

52

53 @Override

54 public boolean onCreateOptionsMenu(Menu menu) {

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

61 public boolean onOptionsItemSelected(MenuItem item) {

62 // Handle action bar item clicks here. The action bar will

63 // automatically handle clicks on the Home/Up button, so long

64 // as you specify a parent activity in AndroidManifest.xml.

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

77 //creating fragment object

78 Fragment fragment = null;

79

80 //initializing the fragment object which is selected

81 switch (itemId) {

82 case R.id.nav_menu1:

83 fragment = new Menu1();

84 break;

85 case R.id.nav_menu2:

86 fragment = new Menu2();

87 break;

88 case R.id.nav_menu3:

89 fragment = new Menu3();

90 break;

91 }

92

93 //replacing the fragment

94 if (fragment != null) {

95 FragmentTransaction ft = getSupportFragmentManager().beginTransaction();

96 ft.replace(R.id.content_frame, fragment);

97 ft.commit();

98 }

99

100 DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);

101 drawer.closeDrawer(GravityCompat.START);

102 }

103

104
105 @SuppressWarnings("StatementWithEmptyBody")

106 @Override

107 public boolean onNavigationItemSelected(MenuItem item) {

108

109 //calling the method displayselectedscreen and passing the id of selected menu

110 displaySelectedScreen(item.getItemId());

111 //make this method blank

112 return true;

113 }

114

115

116 }

 Thats it now just run your application.


Android Navigation Drawer Example

 Bingo! Its working absolutely fine. If you are having troubles you can get the source code
from the below github repository.

You might also like