Notice: A non well formed numeric value encountered in /home/top12rev/public_html/ on line 118

A Proper Way to Implement Back Navigation for Navigation Drawer in Android Studio

Here is a proper way to implement Back Navigation for Navigation Drawer in Android Studio by using Backstack. Every Android device comes a back button. It is one of the cool feature that Android has. Unlike iPhone having only home button where you can go back to previous state easily, Android remember your last state, last page and last fragment.

However, it comes with a price to pay. Fragment in Android can appear on any activity, where you can easily see it on Navigation Drawer (You can watch all the tutorials of Navigation Drawer in YouTube channel Oum Saokosal by clicking this link).

Here is full video tutorial:

Fragment needs to use BackStack to push a Fragment into a stack and pop it back from a stack. Below is an example of a stack of chair:

How do u get a chair at the bottom? Well, you have take one by one out. That is called stack. Similarly in Android Fragment, a first added Fragment is at the bottom, a second one is above bottom. It is First In Last Out (FILO).

Here is sample code if you want to add Fragment into the BackStack:


This code will be called inside the navigation drawer menu call. The most important point here is:


This code will add the frag which is FirstFragment itself into the BackStack. So whenever, you press on a physical Android back button, it goes back a previous Fragment until it reaches the end.


Sometimes in a real word app, you don’t want to go back to any previous Fragment. Instead, you want just to go back to a Home Fragment. This way is quick to browse. Here is the code.
First you need to clear all elements (Fragments) from the the BackStack by using a code line below:

Once you clear all, you can add just only one Fragment, the HomeFragment:

That is it. Now you can implement back navigation properly in the Navigation Drawer.