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 the 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 the “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.
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 a container view for content_main.xml.
  1. public class BaseActivity extends AppCompatActivity
  2. implements NavigationView.OnNavigationItemSelectedListener {
  3. // Declaration
  4. DrawerLayout drawer;
  5. FloatingActionButton fab;
  6. NavigationView navigationView;
  7. @Override
  8. protected void onCreate(Bundle savedInstanceState) {
  9. super.onCreate(savedInstanceState);
  10. setContentView(R.layout.activity_main);
  11. // Initialize Widgets
  12. Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
  13. setSupportActionBar(toolbar);
  14. fab = (FloatingActionButton) findViewById(R.id.fab);
  15. drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
  16. ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
  17. drawer.setDrawerListener(toggle);
  18. toggle.syncState();
  19. navigationView = (NavigationView) findViewById(R.id.nav_view);
  20. navigationView.setNavigationItemSelectedListener(this);
  21. }
  22. @SuppressWarnings("StatementWithEmptyBody")
  23. @Override
  24. public boolean onNavigationItemSelected(@NonNull MenuItem item) {
  25. int id = item.getItemId();
  26. if (id == R.id.nav_activity1) {
  27. startAnimatedActivity(new Intent(getApplicationContext(), FirstActivity.class));
  28. } else if (id == R.id.nav_activity2) {
  29. startAnimatedActivity(new Intent(getApplicationContext(), SecondActivity.class));
  30. }
  31. drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
  32. drawer.closeDrawer(GravityCompat.START);
  33. return true;
  34. }
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 the 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, null, false);
  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. @Override
  3. protected void onCreate(Bundle savedInstanceState) {
  4. super.onCreate(savedInstanceState);
  5. LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  6. //inflate your activity layout here!
  7. @SuppressLint("InflateParams")
  8. View contentView = inflater.inflate(R.layout.activity_first, null, false);
  9. drawer.addView(contentView, 0);
  10. navigationView.setCheckedItem(R.id.nav_activity1);
  11. fab.setOnClickListener(new View.OnClickListener() {
  12. @Override
  13. public void onClick(View view) {
  14. Snackbar.make(view, "Hello First Activity", Snackbar.LENGTH_LONG)
  15. .setAction("Action", null).show();
  16. }
  17. });
  18. }
  19. @Override
  20. public boolean onCreateOptionsMenu(Menu menu) {
  21. // Inflate the menu; this adds items to the action bar if it is present.
  22. getMenuInflater().inflate(R.menu.menu_first, menu);
  23. return true;
  24. }
  25. @Override
  26. public boolean onOptionsItemSelected(MenuItem item) {
  27. // Handle action bar item clicks here. The action bar will
  28. // automatically handle clicks on the Home/Up button, so long
  29. // as you specify a parent activity in AndroidManifest.xml.
  30. int id = item.getItemId();
  31. //noinspection SimplifiableIfStatement
  32. if (id == R.id.action_menu_first) {
  33. return true;
  34. }
  35. return super.onOptionsItemSelected(item);
  36. }
  37. @Override
  38. public void onBackPressed() {
  39. drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
  40. if (drawer.isDrawerOpen(GravityCompat.START)) {
  41. drawer.closeDrawer(GravityCompat.START);
  42. } else {
  43. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
  44. finishAffinity();
  45. } else {
  46. super.onBackPressed();
  47. }
  48. }
  49. }
  50. }
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.