Android Create Navigation Drawer Using Fragments

Android-Navigation-Drawer-Using-Fragments

24th February, 2020

Hello Android Developer!

In this part, You will see how to create Android Navigation Drawer Using Fragments.

Step 1: Create New Project

Create a new project in Android Studio from File ⇒ New Project and select Navigation Drawer Activity from the templates.

Step 2: Modify Drawer Menu

Open the default activity_main_drawer.xml present in menu folder. This is menu file of navigation drawer. You can add or remove menu from here as per your project requirement. I have used three menu in this project.

Project ⇒ app ⇒ src ⇒ main ⇒ res ⇒ menu ⇒

<?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_home"
            android:title="Home" />
        <item
            android:id="@+id/nav_gallery"
            android:icon="@drawable/ic_menu_gallery"
            android:title="Gallery" />
        <item
            android:id="@+id/nav_movies"
            android:icon="@drawable/ic_menu_slideshow"
            android:title="Movies" />
    </group>
</menu>

Step 3: Add Fragments

Next, Create a package namely ‘fragments’ inside root package. Then right click on it and select New ⇒ Fragment ⇒ Fragment (Blank)

Add-New-Fragment
Add New Fragment

Fill the Fragment Name field and hit Finish button.

Create-Fragment-Fragment-Window
Create Fragment Fragment Window

Please repeat this step to create other remaining fragments.

I have created following blank fragments.

package com.codestringz.navigationdrawerwithfragments.fragments;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.codestringz.navigationdrawerwithfragments.R;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

/**
 * A simple {@link Fragment} subclass.
 */
public class HomeFragment extends Fragment
{

    public HomeFragment()
    {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_home, container, false);
    }

    @Override
    public void onResume()
    {
        super.onResume();
        //Set title of this fragment
        if (getActivity() != null)
        {
            getActivity().setTitle("Home");
        }
    }
}
package com.codestringz.navigationdrawerwithfragments.fragments;

import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.codestringz.navigationdrawerwithfragments.R;

/**
 * A simple {@link Fragment} subclass.
 */
public class GalleryFragment extends Fragment
{
    
    public GalleryFragment()
    {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_gallery, container, false);
    }

    @Override
    public void onResume()
    {
        super.onResume();
        //Set title of this fragment
        if (getActivity() != null)
        {
            getActivity().setTitle("Gallery");
        }
    }
}
package com.codestringz.navigationdrawerwithfragments.fragments;

import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.codestringz.navigationdrawerwithfragments.R;

/**
 * A simple {@link Fragment} subclass.
 */
public class MoviesFragment extends Fragment
{
    
    public MoviesFragment()
    {
        // Required empty public constructor
    }
    
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_movies, container, false);
    }

    @Override
    public void onResume()
    {
        super.onResume();
        //Set title of this fragment
        if (getActivity() != null)
        {
            getActivity().setTitle("Movies");
        }
    }
}
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".fragments.HomeFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="This is Home fragment" />

</FrameLayout>
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".fragments.GalleryFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="This is Gallery fragment" />

</FrameLayout>
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".fragments.MoviesFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="This is Movies fragment" />

</FrameLayout>

Step 3: Modify Main Activity

After that, Now all you need to do is add some code to the main activity that connects your fragments to the navigation drawer. Let’s see.

package com.codestringz.navigationdrawerwithfragments;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.view.View;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

import com.codestringz.navigationdrawerwithfragments.fragments.GalleryFragment;
import com.codestringz.navigationdrawerwithfragments.fragments.HomeFragment;
import com.codestringz.navigationdrawerwithfragments.fragments.MoviesFragment;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.snackbar.Snackbar;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener
{

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        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);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        //Create Home Fragment object
        HomeFragment homeFragment = new HomeFragment();

        //--------Set Home fragment as default fragment-------//
        setMyFragment(homeFragment);
    }

    @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.main, 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)
        {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item)
    {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_home)
        {
            // Home Fragment
            HomeFragment homeFragment = new HomeFragment();
            setMyFragment(homeFragment);

        } else if (id == R.id.nav_gallery)
        {
            // Gallery Fragment
            GalleryFragment galleryFragment = new GalleryFragment();
            setMyFragment(galleryFragment);
        } else if (id == R.id.nav_movies)
        {
            // Movies Fragment
            MoviesFragment moviesFragment = new MoviesFragment();
            setMyFragment(moviesFragment);
        }

        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    private void setMyFragment(Fragment fragment)
    {
        //get current fragment manager
        FragmentManager fragmentManager = getSupportFragmentManager();

        //get fragment transaction
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        //set new fragment in fragment_container (FrameLayout)
        fragmentTransaction.replace(R.id.fragment_container, fragment);
        fragmentTransaction.commit();
    }
}

That’s it. Run your app. Happy coding!

Video Tutorial

2 Comments

  1. Hi, there. I like this lecture. Thank you. I am a beginner. I am making app with Navigation drawer. I want to make like this. There is a function for crawling web and when I click one of menu buttons on drawer bar, I want to see the result of crawling on some fragment. I tried again & again. But I couldn’t make this. Can u help me to make this function?

    1. Hi, Thanks for asking the question. Please refer the demo code given below. Hope you can get some ideas.

      public class ResultFrag extends Fragment
      {
          private static final String ARG_PARAM1 = "param1";
          private static final String ARG_PARAM2 = "param2";
          private OnFragInterListener mListener;
      
          public ResultFrag(){}
      
      	//change parameters ('param1', 'param2') with your requirement
          public static ResultFrag newInstance(String param1, String param2)
          {
              ResultFrag fragment = new ResultFrag();
              Bundle args = new Bundle();
              args.putString(ARG_PARAM1, param1);
              args.putString(ARG_PARAM2, param2);
              fragment.setArguments(args);
              return fragment;
          }
      	
      	@Override
          public void onStart()
          {
              super.onStart();
      		
      		if (getArguments() != null)
                  {
      			    //display result
      				
                      String name1 = getArguments().getString(ARG_PARAM1);
                      String name2 = getArguments().getString(ARG_PARAM2);
      				
      				name1TextView.setText(name1);
      				name2TextView.setText(name2);
      			}
      	}
      }
      //THIS IS JUST DEMONSTRATION CODE
      
      public class MainActivity extends AppCompatActivity
              implements NavigationView.OnNavigationItemSelectedListener 
      {
      public boolean onNavigationItemSelected(MenuItem item) {
              // Handle navigation view item clicks here.
              int id = item.getItemId();
      
              if (id == R.id.nav_test)
              {
                  // Handle the action
                  setWebResultFrag();
      			
              } else if (id == R.id.nav_gallery)
              {
                  //....
              } 
      
              DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
              drawer.closeDrawer(GravityCompat.START);
              return true;
          }
      	
      	private void setWebResultFrag()
          {
      		//create parameter objects as per your requirement for example web results, etc
      		String str1="hello1";
      		String str2="hello2";
      		
      		//result fragment instance
      		Fragment resultFragment = ResultFrag.newInstance(str1, str2);
      		
              FragmentManager manager = getSupportFragmentManager();
              FragmentTransaction transaction = manager.beginTransaction();
              transaction.replace(R.id.frags, resultFragment);
              
              transaction.commit();
      
          }
      }
      
      //THIS IS JUST DEMONSTRATION CODE
      

      Happy coding!

Leave a Reply