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:
android.support.v4.app.Fragment frag; frag = new FirstFragment(); getSupportFragmentManager().beginTransaction() .addToBackStack(null) //add itself (FirstFragment) into the stack .replace(R.id.mainLayout, frag) .commit();
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.
HOW TO GO BACK TO HOME FRAGMENT?
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:
android.support.v4.app.Fragment frag; frag = new FirstFragment(); getSupportFragmentManager().beginTransaction() // add HomeFragment only .add(new HomeFragment(), "HomeFragment") .addToBackStack("HomeFragment").replace(R.id.mainLayout, frag) // end of adding HomeFragment .commit();
That is it. Now you can implement back navigation properly in the Navigation Drawer.