Custom Android Navigation Drawer

In this blog post ,I will show a walk-through on how to create a custom Navigation Drawer using the auto generated Android Studio Navigation Drawer template. This also applies if you are working with the ADT plugin in Eclipse. Using the auto generated Android Studio Navigation Drawer gives you are great head start for most of the use cases of Navigation Drawer; however it can also leave you in the middle of nowhere if you want to apply some customization. Here is what our demo app will look like when completed.

Project Creation

If you want to follow along, go ahead and create a new Android project using Android Studio, I have named my project NavigationDrawerExample. Select the new project template, select Phone and Tablet as your target devices and choose any API level you want to target for this project I selected API level 16. Click next and select Activity with Navigation like the image below:

Click next and feel free to leave the default name of MainActivity, we are only going to be using one Activity for this demo. Once the project is created, you will notice one little departure from the former template which is that the Navigation Drawer boiler plate codes are now defined in a new Fragment called NavigationDrawerFragment instead of inside the MainActivity. And out of the box, this implementation provides the core functions of a Navigation Drawer including opening up on first use and listening to see if the user has learned about the Navigation drawer for the first time so that it will stop showing on start up. It handles switching the title to show the currently selected Fragment.

What is missing?

First there is this embedded Fragment called PlaceHolderFragment that seems to confuse some people

How do we add more Fragments to the Navigation Drawer list

How do we add images to the Navigation Drawer list

How do we navigate to lower level Fragments that are not represented in the Navigation Drawer list

How do we swtich between the Navigation Drawer icon (hamburger) and Actionbar Up caret button

How do we update the title of the Actionbar to show titles of lower level Fragments

Step 1 – Add Fragments

Go ahead and add all of your fragments if you know them ahead. For this demo project, I have added the following Fragments in a Package I called Fragments. No functionality is actually implemented in these fragments, they are used as demo fragment to demonstrate Navigation Drawer

CustomerListFragment

CustomerDetailFragment

ProductListFragment

ProductDetailFragment

OrderListFragment

OrderDetailsFragment

Step 2: Add DrawerItem

This is not required but very very helpful. Each item in our improved Navigation Drawer list will have two elements, an image (icon) and a text which is the name of the Fragment we want to go to. So we will define a Java class that will hold exactly those two elements and you will see its usage as we proceed. So please go ahead and create another Package called Model and add a Java class called DrawerItem.java with the content below:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

publicclassDrawerItem{

StringItemName;

intimgResID;

publicDrawerItem(StringitemName,intimgResID){

super();

ItemName=itemName;

this.imgResID=imgResID;

}

publicStringgetItemName(){

returnItemName;

}

publicvoidsetItemName(StringitemName){

ItemName=itemName;

}

publicintgetImgResID(){

returnimgResID;

}

publicvoidsetImgResID(intimgResID){

this.imgResID=imgResID;

}

}

If you are following along, then your project structure should look like the image below:Step 3 – Add Navigation Drawer List Icons
If you want your Navigation Drawer list items to have icons to their right, go ahead and add those icons to the drawables now. If you do not have existing icons save yourself some time and head over to Roman Nurik Android Asset Studio and generate the needed icons. That is exactly what I did for this demo project. Copy those icons over to your drawables folder. When you download the icons they will be in zip files, unzip the files and drop the drawable folders to your res folder, Android Studio will make sure that that each image go to their respective folders hdpi, mdpi, etc.

Step 4 – Create a new Adapter
If you look at the NavigationFragment, you will notice that it uses an inline Adapter to manage the Navigation Drawer and supplied a static list of String like so:

1

2

3

4

5

6

7

8

9

mDrawerListView.setAdapter(newArrayAdapter(

getActionBar().getThemedContext(),

android.R.layout.simple_list_item_activated_1,

android.R.id.text1,

newString[]{

getString(R.string.title_section1),

getString(R.string.title_section2),

getString(R.string.title_section3),

}));

Since our improved Navigation Drawer list will have an image and a text we need to supply our own custom adapter. Before we create the custom adapter, we need to define how each row in that custom list will look like. So go to your layout folder in the res folder and add the following xml layout file. I have named mine custom_drawer_item.xml and here is the content:

1

With the row layout defined, go ahead and create a Java class, I have named mine CustomerDrawerAdapter.java and placed it in an Adapter package. And here is the content of that adapter:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

publicclassCustomDrawerAdapterextendsArrayAdapter{

Context context;

List drawerItemList;

intlayoutResID;

publicCustomDrawerAdapter(Context context,intlayoutResourceID,

List listItems){

super(context,layoutResourceID,listItems);

this.context=context;

this.drawerItemList=listItems;

this.layoutResID=layoutResourceID;

}

@Override

publicView getView(intposition,View convertView,ViewGroup parent){

// TODO Auto-generated method stub

DrawerItemHolder drawerHolder;

View view=convertView;

if(view==null){

LayoutInflater inflater=((Activity)context).getLayoutInflater();

drawerHolder=newDrawerItemHolder();

view=inflater.inflate(layoutResID,parent,false);

drawerHolder.ItemName=(TextView)view

.findViewById(R.id.drawer_itemName);

drawerHolder.icon=(ImageView)view.findViewById(R.id.drawer_icon);

view.setTag(drawerHolder);

}else{

drawerHolder=(DrawerItemHolder)view.getTag();

}

DrawerItem dItem=(DrawerItem)this.drawerItemList.get(position);

drawerHolder.icon.setImageDrawable(view.getResources().getDrawable(

dItem.getImgResID()));

drawerHolder.ItemName.setText(dItem.getItemName());

returnview;

}

privatestaticclassDrawerItemHolder{

TextView ItemName;

ImageView icon;

}

}

Step 5 – Replace the default Adapter
Now that we have created our custom adapter, we need to replace the default adapter generated by Android Studio. Before we do that, remember that the generated adapter has an inline array of Strings, well we need to replace that too with another list of something that contains our fragments. At the top of the NavigationDrawer element go ahead and add these to lines of code:

1

2

privateList dataList;

privateCustomDrawerAdapter mDrawerAdapter;

Now go down, under the onCreateView() method and instantiate the list that you defined above with the code below, remember our DrawerItem class, now its coming to good use.

1

dataList=newArrayList();

Next, replace the code that created the inline adapter with an instance of our custom adapter and supply our custom row layout like below:

Now if you run the project, nothing will actually show in the list because we have not supplied our list with any item. So under where you instantiated the datalist, add a method to populate the list. I have called my method addItemsToDataList so it looks like this:

1

2

dataList=newArrayList();

addItemsToDataList();

Now go anywhere in the NavigationDrawerFragment class to define the method like below, I put mine at the bottom of the class.

Here is where you add your top level fragments. The ones you want to show in the Navigation Drawer listview. You do not have to add your low level fragments here like the details fragments we created earlier. If you run the app now, you will see the image below. Go ahead and make sure you can run the app and it shows the screen below as we proceed to add Actionbar behavior next.

Step 6 – Update Title
The default behaviour of Navigation Drawer is to show the title of the currently selected Fragment in the Navigation drawer. We will update the default template to also account for our lower lower fragment. The title is updated in the MainActivity, it has a method called onSectionAttached and accepts an int like so:

1

2

3

4

5

6

7

8

9

10

11

12

13

publicvoidonSectionAttached(intnumber){

switch(number){

case1:

mTitle=getString(R.string.title_section1);

break;

case2:

mTitle=getString(R.string.title_section2);

break;

case3:

mTitle=getString(R.string.title_section3);

break;

}

}

Update the code to show Customer, Products, Order, etc to reflect the names you want to show for each of your Fragment. You can also add add your order lower lever fragment.Now, how does it know which one to show, it gets it from the supplied int parameter and this parameter and this parameter is supplied via the NewInstance method of each fragment. Here is my updated onSectionAttachedMethod:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

publicvoidonSectionAttached(intnumber){

switch(number){

case0:

mTitle=getString(R.string.title_section0);

break;

case1:

mTitle=getString(R.string.title_section1);

break;

case2:

mTitle=getString(R.string.title_section2);

break;

case3:

mTitle=getString(R.string.title_section3);

break;

case4:

mTitle=getString(R.string.title_section4);

break;

case5:

mTitle=getString(R.string.title_section5);

break;

}

}

Step 7 – Create New Fragment
Currently the auto generated code uses PlaceHolderFragment and for each time something is selected in the Navigation list like this:

1

2

3

4

5

6

7

8

@Override

publicvoidonNavigationDrawerItemSelected(intposition){

// update the main content by replacing fragments

FragmentManager fragmentManager=getSupportFragmentManager();

fragmentManager.beginTransaction()

.replace(R.id.container,PlaceholderFragment.newInstance(position+1))

.commit();

}

We will update this to actually start creating something when its clicked. Delete the PlaceHolder Fragment. We need to create the fragments using their respective newInstance method. NewInstance is a thoroughly debated and generally accepted design pattern that you will do well to follow.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

@Override

publicvoidonNavigationDrawerItemSelected(intposition){

Fragment mFragment=null;

switch(position){

case0:

mFragment=CustomerListFragment.newInstance(0);

break;

case1:

mFragment=ProductListFragment.newInstance(1);

break;

case2:

mFragment=OrderListFragment.newInstance(2);

break;

}

FragmentManager fragmentManager=getSupportFragmentManager();

fragmentManager.beginTransaction()

.replace(R.id.container,mFragment)

.addToBackStack(null)

.commit();

}

For each of your fragment add or update the newInstance method like this:

1

2

3

4

5

6

7

publicstaticCustomerListFragment newInstance(intsectionNumber){

CustomerListFragment fragment=newCustomerListFragment();

Bundle args=newBundle();

args.putInt(Constants.ARG_SECTION_NUMBER,sectionNumber);

fragment.setArguments(args);

returnfragment;

}

I defined a constant to hold the reference like so:

1

publicstaticfinalStringARG_SECTION_NUMBER="section_number";

Then in the onAttach() method of each of your fragment, call the onSectionAttached method of your MainActivity, to update the title with whatever title you supplied to that number. Here is the onAttach callback method:

1

2

3

4

5

6

@Override

publicvoidonAttach(Activity activity){

super.onAttach(activity);

((MainActivity)activity).onSectionAttached(

getArguments().getInt(Constants.ARG_SECTION_NUMBER));

}

Make sure that your Fragments are using the Support library fragment. You will need to define the NewInstance methods and the onAttach call back methods for your lower level Activities.

Step 7 – Add Lower Level Fragments
You can go to your lower level Fragment any way that makes sense for your app. It could be through an onClickListner event in your listview. It could be through a menu item. Either way, you should probably be aware that it is not recommended that you start a Fragment from a Fragment, so you will need to call the Activity and inform it to start a Fragment for you. One way you can accomplish this it to create a method in the MainActivity that does this.

Then you can make that method accept an int and then create a switch statement using that int. Or better still, you can create an Enum so you will not have to be remembering numbers. Below is an example of how you can start a new fragment from a menu and example of a method in the ReplaceFragment method in the Main Activity.

First add a menu item xml like this

1

Then in the CustomerListFragment, add and handle the menu icon to create a lower level Fragment like this:

Step 8 – Switch the Navigation Drawer Icon with the Up Icon for Lower Level Fragments
Notice that in the above call in the Fragment, we are calling a method in the Main Activity. What this method does,is first it hides the Navigation Drawer icon and then start the called fragment. To actually make the Up button to show in the Action bar, you will have to first call SetHasOptionMenu in each of the lower level Fragment to show the menu items and then call set display Action bar up button like so:

Step 9 – Go Back to Parent Fragment
To go back to a parent Fragment from a lower level Fragment, you override the OnBackPressed of the Main Activity like this:

1

2

3

4

5

6

7

8

@Override

publicvoidonBackPressed(){

super.onBackPressed();

NavigationDrawerFragment navFrag=(NavigationDrawerFragment)

getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);

navFrag.mDrawerToggle.setDrawerIndicatorEnabled(true);

onSectionAttached(navFrag.mCurrentSelectedPosition);

}

Then each time you want to back to a parent Fragment you call that method from a lower level Fragment like this:

1

2

3

4

5

6

7

8

9

@Override

publicbooleanonOptionsItemSelected(MenuItem item){

switch(item.getItemId()){

caseandroid.R.id.home:

getActivity().onBackPressed();

break;

}

returnsuper.onOptionsItemSelected(item);

}

Points to Note

All your Fragment will be from the Support Library otherwise you will get error when you call getSupportFragmentManager

This does not work with Toolbar, atleast not without significant hack as shown in this StackOverFlow question

You do not need a custom adapter if you do not need an image in the Navigation Drawer List

Remove the action_example menu item from main.xml in the menu.

The mDrawerToggle and mCurrentSelectionPosition in the NavigationFragment should be made public so it can be accessible from the MainActivity

Summary
That is it, this should get you a working custom Navigation Drawer that you further flush out to fit your project. You can find the source code for the demo project from my Github repo and if you do something interesting with it please submit a pull request so others can benefit from it. And if you find something not working please use the comment to let me know. Thanks for reading.In