How to use navigation drawer activity in Android Studio

[This post was updated on 13-03-2017 ]

We will show you the correct way of creating navigation drawer in android .

1.  We will deal with error cause by : onFragmentInteraction

2. Set a drawer element selected by default.

3. Change toolbar title based on active fragment.


  1. We have started to use Fragments instead of Activities. ( in short, fragments are light weight)
  2. To create Fragments in your main project  i.e Right click on the project folder -> New -> Fragments -> Fragment (Blank).
  3.  <FrameLayout> </FrameLayout> is used as a container for Fragments
  4. Code for Fragment Switching:
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(, new Fragment1());



[wpi_designer_button text=’Download’ link=’; style_id=’48’ icon=’github’ target=’_blank’]


  1. Create a new Android Project  ->  Minimum SDK: 15  -> Navigation Drawer Activity -> Finish.

How to use navigation layout activity in android studio

2. Now let us examine the files that are automatically generated by Android studio.

Layout Folder:

  • content_main.xml : This is basically the First Screen i.e initially it contains only a TextView with Hello World!!We will replace the inner content with <frame-layout> , so that we can display our fragments.


  • app_bar_main.xml: Contains the Toolbar overlay and Floating button.


  • nav_header_main.xml: Contains a part of navigation drawer.


  • activity_main.xml: Links  app_bar_main  &  nav_header_main (the menu items are added from menu/activity_main_drawer.xml )

Menu Folder:

  • menu/main.xml: Contains the menu items for App Tool Bar (By default it will contain only settings)


  • menu/activity_main_drawer.xml : Contains the menu items for navigation drawer.

Java Package Folder: : The main java file where you write the code (Basically onClickListeners  for navigation drawer menus and Tool bar menus.)



1. Hope you have already created a navigation drawer project.

2. Create a new Fragment. Name it as Fragment 1.

3. Create 2 other fragments. Name them as Fragment2  and Fragment3.

4. Open content_main.xml and replace the inner textfield with framelayout.

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

    <!-- Note : This is the container Frame Layout for all the fragmetns-->


5. Since we have created only three fragments, we will modify the drawer menu, so that it displays only three options.

Goto : res > menu > activity_main_drawer.xml . Replace its contents with the following

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="">

    <!-- Note:  android:checkableBehavior="single" -->
    <group android:checkableBehavior="single">
            android:title="Fragment 1" />
            android:title="Fragment 2" />
            android:title="Fragment 3" />



6. Now comes the .

(1) In the onCreate() add the following to the end of the function.

       //NOTE:  Checks first item in the navigation drawer initially

        //NOTE:  Open fragment1 initially.
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(, new Fragment1());


(2) Replace onNavigationItemSelected()

    public boolean onNavigationItemSelected(MenuItem item) {
        int id = item.getItemId();

        //NOTE: creating fragment object
        Fragment fragment = null;

        if (id == {
            fragment = new Fragment1();
        } else if (id == {
            fragment = new Fragment2();
        }else if (id == {
            fragment = new Fragment3();

        //NOTE: Fragment changing code
        if (fragment != null) {
            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            ft.replace(, fragment);

        //NOTE:  Closing the drawer after selecting
        DrawerLayout drawer = (DrawerLayout) findViewById(; //Ya you can also globalize this variable 😛
        return true;


(3) In the extends AppCompactActivity implements part , add the OnFragmentInteractionListener for all the 3 fragments.

public class MainActivity extends AppCompatActivity

        //Note : OnFragmentInteractionListener of all the fragments

        NavigationView.OnNavigationItemSelectedListener {

    protected void onCreate(Bundle savedInstanceState) {


(4) Now un/fortunately you will be seeing a whole bunch of red underlinings. Dont worry, press Alt + Enter and resolve the error by auto implementing onFragmentInteraction()

Why do we need it ? Basically, I use to set the toolbar title when i toggle between different fragments.

So let modify it accordingly.

    public void onFragmentInteraction(String title) {
        // NOTE:  Code to replace the toolbar title based current visible fragment

We are done with the

7. We will now open There is hell alot of boiler plate code in there.

Just to give a brief overview. ( Deviating from the main course)

  • public static Fragment1 newInstance() is use for creating fragment objects passing some parameters.
  • public void onCreate() is used for initializing/doing some non graphical things. For eg:- Initializing firebase database, or gps object. ( Do not use include functions that will modify the android screen here. It will bring crashes, as view object is created.)
  • onAttach() is called when fragment 1 is currently being displayed. For eg:- You can start the locationChangeListner() for map in case, you are view the map fragment.
  • onDetach() is called when fragment 1 is now removed from the displayed view. You can pause locationChangeListner() as you don’t need to update the data into map, when you are not looking at the map fragment.
  • onBackPressed() just remove it 😛
  • onCreateView() is the part where fragments view is set, ie the GUI part of fragment.  (Coming back to the main course)
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View view= inflater.inflate(R.layout.fragment_fragment1, container, false);
            // NOTE : We are calling the onFragmentInteraction() declared in the MainActivity
            // ie we are sending "Fragment 1" as title parameter when fragment1 is activated
            if (mListener != null) {
                mListener.onFragmentInteraction("Fragment 1");
            // Here we will can create click listners etc for all the gui elements on the fragment.
            // For eg: Button btn1= (Button) view.findViewById(;
            // btn1.setOnclickListener(...
            return view;
  • OnFragmentInteractionListener() we will pass the needed title for fragment to MainActivity here.

       public interface OnFragmentInteractionListener {
           // NOTE : We changed the Uri to String.
            void onFragmentInteraction(String title);

8. Repeat the same for other two fragments.

Hope this helped someone !


4 thoughts on “How to use navigation drawer activity in Android Studio

  1. There’s no need to change:

    Because you can replace:

    Fragment fragment = new FragmentMain();
    FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.replace(, fragment);

    to this:

    FragmentMain fragmentMain = new FragmentMain();


  2. I tried to connect navigation drawers & tabbed activity but its not working. Can you please explain me in detail. how to connect navigation drawers & tabbed activity


  3. I want to change drawer item icons, when i select different drawable file, app crashes.
    Default drawable are v21, and the one which i am adding, are v24. What should be the fix?


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s