Navigation Drawer Activity In Android

Android

Introduction

In this article, we will learn how to use a single Navigation Drawer for different activities. Navigation Drawer is an important widget in the Android application. Mostly, fragments are used in navigation view to load different screens based on the user selection. But, the usage of Fragments with Navigation may lead to back stack issues sometimes. Instead of using fragments, we can use this approach which is very easy to implement.

Steps

I have split this approach into steps as shown below.

Step 1

Create a new project with Navigation Drawer Activity.

Step 2

Create a BaseActivity extended with AppCompatActivity.

Step 3

Create Activities extended with BaseActivity.

Step 4

Adding the functionalities to perform Navigation menu operations.

Without any more introduction, we will jump into the coding part.

Step 1

  1. Open Android Studio and create a new project.
  2. Name the project as per your wish and select the Navigation Drawer activity.

    Android

  1. Click “Finish” button to create a new project in Android Studio.

Step 2

  1. In this step, we will rename the Navigation Drawer activity into “BaseActivity”. For example, I have renamed the “MainActivity” to “BaseActivity”.

  2. Change the default coding part of your BaseActivity as shown below.
    • The parent of this Activity is AppCompatActivity. So, this BaseActivity can be used as Parent Activity for others to access the properties of AppCompatActivity.
    • This Activity is implemented with OnNavigationItemSelectedListener. So, here you can handle the navigation of activities.

Coding Part

Create content_main.xml file and add FrameLayout as Parent Layout as shown below. This Frame Layout is used to bind the layout of children layouts.

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     xmlns:tools="http://schemas.android.com/tools"  
  4.     android:id="@+id/content_frame"  
  5.     android:layout_width="match_parent"  
  6.     android:layout_height="match_parent"  
  7.     tools:context="com.androidmads.navdraweractivity.BaseActivity"  
  8.     tools:showIn="@layout/app_bar_main" />  

Here, the FrameLayout has the id as "content_frame" is used to hold the activity's view.

Open your BaseActivity.java file and add the following code. Here, activity_main.xml is container view for content_main.xml.

  • Drawer Layout is used to implement the Sidemenu in Android.
  • Here, class and SecondActivity.class are used as children activities of BaseActivity.
  1. public class BaseActivity extends AppCompatActivity  
  2.  implements NavigationView.OnNavigationItemSelectedListener {  
  3.   
  4. // Declaration  
  5. DrawerLayout drawer;  
  6. FloatingActionButton fab;  
  7. NavigationView navigationView;  
  8.   
  9. @Override  
  10. protected void onCreate(Bundle savedInstanceState) {  
  11.  super.onCreate(savedInstanceState);  
  12.  setContentView(R.layout.activity_main);  
  13.    
  14.  // Initialize Widgets  
  15.  Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);  
  16.  setSupportActionBar(toolbar);  
  17.   
  18.  fab = (FloatingActionButton) findViewById(R.id.fab);  
  19.  drawer = (DrawerLayout) findViewById(R.id.drawer_layout);  
  20.  ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);  
  21.  drawer.setDrawerListener(toggle);  
  22.  toggle.syncState();  
  23.    
  24.  navigationView = (NavigationView) findViewById(R.id.nav_view);  
  25.  navigationView.setNavigationItemSelectedListener(this);  
  26. }  
  27.   
  28. @SuppressWarnings("StatementWithEmptyBody")  
  29. @Override  
  30. public boolean onNavigationItemSelected(@NonNull MenuItem item) {  
  31.  int id = item.getItemId();  
  32.  if (id == R.id.nav_activity1) {  
  33.   startAnimatedActivity(new Intent(getApplicationContext(), FirstActivity.class));  
  34.  } else if (id == R.id.nav_activity2) {  
  35.   startAnimatedActivity(new Intent(getApplicationContext(), SecondActivity.class));  
  36.  }  
  37.   
  38.  drawer = (DrawerLayout) findViewById(R.id.drawer_layout);  
  39.  drawer.closeDrawer(GravityCompat.START);  
  40.  return true;  
  41. }  

Here, startAnimatedActivity(intent) used to start activity with animation.

Step 2

  1. Create a New Activity and name it as java and change the parent of this class from AppCompatActivity to BaseActivity as we created.
  2. Again, create a New Activity named as java and change the parent of this class from AppCompatActivity to BaseActivity as we created.

Step 3

  1. Replace setContentView in onCreate method of the class files created in step2 as shown below.

Coding Part

  1. setContentView(R.layout.activity_first)  
  2. To   
  3. LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);  
  4. //inflate your activity layout here!  
  5. @SuppressLint("InflateParams")  
  6. View contentView = inflater.inflate(R.layout.activity_first, nullfalse);  
  7. drawer.addView(contentView, 0);  

Here, activity_first.xml is the designer layout of the activity FirstActivity.java

This approach is used to inflate or bind the layouts in BaseActivity

Full code for FirstActivity.java

  1. public class FirstActivity extends BaseActivity {  
  2.   
  3.     @Override  
  4.     protected void onCreate(Bundle savedInstanceState) {  
  5.         super.onCreate(savedInstanceState);  
  6.         LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);  
  7.         //inflate your activity layout here!  
  8.         @SuppressLint("InflateParams")  
  9.         View contentView = inflater.inflate(R.layout.activity_first, nullfalse);  
  10.         drawer.addView(contentView, 0);  
  11.         navigationView.setCheckedItem(R.id.nav_activity1);  
  12.         fab.setOnClickListener(new View.OnClickListener() {  
  13.             @Override  
  14.             public void onClick(View view) {  
  15.                 Snackbar.make(view, "Hello First Activity", Snackbar.LENGTH_LONG)  
  16.                         .setAction("Action"null).show();  
  17.             }  
  18.         });  
  19.   
  20.     }  
  21.   
  22.     @Override  
  23.     public boolean onCreateOptionsMenu(Menu menu) {  
  24.         // Inflate the menu; this adds items to the action bar if it is present.  
  25.         getMenuInflater().inflate(R.menu.menu_first, menu);  
  26.         return true;  
  27.     }  
  28.   
  29.     @Override  
  30.     public boolean onOptionsItemSelected(MenuItem item) {  
  31.         // Handle action bar item clicks here. The action bar will  
  32.         // automatically handle clicks on the Home/Up button, so long  
  33.         // as you specify a parent activity in AndroidManifest.xml.  
  34.         int id = item.getItemId();  
  35.   
  36.         //noinspection SimplifiableIfStatement  
  37.         if (id == R.id.action_menu_first) {  
  38.             return true;  
  39.         }  
  40.   
  41.         return super.onOptionsItemSelected(item);  
  42.     }  
  43.   
  44.     @Override  
  45.     public void onBackPressed() {  
  46.         drawer = (DrawerLayout) findViewById(R.id.drawer_layout);  
  47.         if (drawer.isDrawerOpen(GravityCompat.START)) {  
  48.             drawer.closeDrawer(GravityCompat.START);  
  49.         } else {  
  50.             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {  
  51.                 finishAffinity();  
  52.             } else {  
  53.                 super.onBackPressed();  
  54.             }  
  55.         }  
  56.     }  
  57. }  

Here, I have overridden the onBackPressed method to close DrawerLayout and close the application.

In this way, you can use the same NavigationView for all the activities. We can create other activities with the same approach to show NavigationView.

Note

Don’t forget to change your launcher activity into FirstActivity.

Download Code

You can download the full source code for this article from GitHub.

Next Recommended Readings